Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a comma separated string of double values into a double array in Java8

I have a String containing double values such as:

String str = "0.1,0.4,0.9,0.1";

I want to get a double array from this string like this:

double[] arr = {0.1, 0.4, 0.9, 0.1};

The most obvious way to do this for me is:

String[] tokens = str.split(",");
double[] arr = new double[tokens.length];
int i=0
for (String st : tokens) {
    arr[i++] = Double.valueOf(st);
}

is there some faster/better way to do that other than the one mentioned above in Java 8?

like image 752
Sumit Avatar asked Jan 30 '23 09:01

Sumit


1 Answers

You can use Streams:

double[] arr = Stream.of(str.split(","))
                     .mapToDouble (Double::parseDouble)
                     .toArray();
like image 170
Eran Avatar answered Jan 31 '23 22:01

Eran