How to convert String Array to Double Array in one line

I have a string array:

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

All String values ​​are numbers. Data must be converted to Double[] .

Question
Is there one Java solution to achieve this, or do we need to loop and convert each value to Double?

+6
source share
7 answers

Create a method that implements it using a loop, then call your method and you will have a one-line solution.

There is no buit-in method in the Java API.

+6
source

The Java 8 Stream API allows you to:

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

A double colon is used as a reference to a method. More details here .

Before using the code, do not forget to import java.util.Arrays;

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

 Double[] doubleValues = Arrays.stream(guaranteedOutput) .map(Double::valueOf) .toArray(Double[]::new); 
+19
source

In one line: p

 Double[] d=new ArrayList<Double>() {{for (String tempLongString : tempLongStrings) add(new Double(tempLongString));}}.toArray(new Double[tempLongStrings.length]); 
+5
source
 CollectionUtils.collect(guaranteedOutput, new Transformer() { public Object transform(Object i) { return Double.parseDouble(i); } }); 

EDIT

Keep in mind that this is not in the JavaSDK! I am using http://commons.apache.org/collections/apidocs/org/apache/commons/collections/CollectionUtils.html

+1
source

You need a card operation from functional programming, unfortunately, Java does not offer. Instead, you should focus on

 double[] nums = new double[guaranteedOutput.length]; for (int i = 0; i < nums.length; i++) { nums[i] = Double.parseDouble(guaranteedOutput[i]); } 
+1
source

I think you will have to iterate and convert each value to double. So I did this in one of my other questions:

 for(getData : getDataArray){ double getTotal; getTotal = getTotal + Double.parseDouble(getData); } return getTotal; 

The idea is the same. Turn this into a method, pass your parameters, and you are golden.

0
source

What is wrong in the loop?

 double[] parsed = new double[values.length]; for (int i = 0; i<values.length; i++) parsed[i] = Double.valueOf(values[i]); 

not particularly awkward. In addition, you can easily add the correct error handling.

Of course, you can easily wrap this as you like.

OpenJDK8 is likely to bring lambda expressions, and using Double.valueOf as the "map" function will be a prime example for this.

0
source

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


All Articles