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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With