Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String Array to Double Array in one line

Tags:

java

I have a string array as:

String[] guaranteedOutput = Arrays.copyOf(values, values.length,
String[].class);

All the String values are numbers. The data should be converted to a Double[].

Question
Is there a one line solution in Java to achieve this or we need to loop and convert each value to a Double?

like image 810
daydreamer Avatar asked Feb 01 '12 18:02

daydreamer


1 Answers

Java 8 Stream API allows to do this:

double[] doubleValues = Arrays.stream(guaranteedOutput)
                        .mapToDouble(Double::parseDouble)
                        .toArray();

Double colon is used as a method reference. Read more here.

Before using the code don't forget to import java.util.Arrays;

UPD: If you want to cast your array to Double[], not double[], you can use the following code:

Double[] doubleValues = Arrays.stream(guaranteedOutput)
                        .map(Double::valueOf)
                        .toArray(Double[]::new);
like image 113
Michael Berdyshev Avatar answered Oct 23 '22 14:10

Michael Berdyshev