Split 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 as follows:

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 a faster / better way to do this other than described above in Java 8?

+4
source share
1 answer

You can use Streams:

double[] arr = Stream.of(str.split(","))
                     .mapToDouble (Double::parseDouble)
                     .toArray();
+7
source

Source: https://habr.com/ru/post/1687963/


All Articles