Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java split string to Double[ ]

I have this string:

((39.4189453125 37.418708616699824,42.0556640625 37.418708616699824,43.4619140625 34.79181436843146,38.84765625 33.84817790215085,39.4189453125 37.418708616699824))

I want to convert it to Double [] java array.

I have tried:

String[]tokens = myString.split(" |,");
Arrays.asList(tokens).stream().map(item -> Double.parseDouble(item)).collect(Collectors.toList()).toArray();

Is there any nicer and more efficient way instead of the array-list-array conversion ?

like image 703
Elad Benda2 Avatar asked Nov 29 '22 22:11

Elad Benda2


2 Answers

Pattern pattern = Pattern.compile("-|\\.");

pattern.splitAsStream(test) // your String
       .map(Double::parseDouble)
       .toArray(Double[]::new);

Also your pattern looks weird, seems like this would fit better [-,\\s]+

like image 177
Eugene Avatar answered Dec 04 '22 09:12

Eugene


Here is how you can do it using doubles instead of Doubles.

String string = "1 2 3 4";
Pattern pattern = Pattern.compile(" |,");

double[] results = pattern.splitAsStream(string)
                          .mapToDouble(Double::parseDouble)
                          .toArray();
like image 36
khelwood Avatar answered Dec 04 '22 11:12

khelwood