Java 8 Lambda to convert Number [] [] to double [] []

Number[][] intArray = new Integer[][]{ {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; double[][] doubleArray = Arrays.stream(intArray) .forEach(pArray -> Arrays.stream(pArray) .mapToDouble(d ->d.doubleValue()) .toArray()) .toArray(); 

I want to convert Number [] [] to double [] []. The above lambda does not work, external toArray does not compile.

Arrays.stream (intArray): returns a stream Integer []
forEach: for each Integer [] creating a stream of integers, converting each Integer to double and returning double [].
Double [] is created for each, and I thought that the external toArray will return an array of this double []
How can I make this work?

+6
source share
2 answers

Here is how you could do it:

 double[][] doubleArray = Arrays.stream(intArray) .map(arr -> Stream.of(arr).mapToDouble(Number::doubleValue).toArray()) .toArray(double[][]::new); 

It can be decomposed as follows:

First you use Arrays.stream to create a Stream<Number[]> . Then for each Number[] you create a Stream<Number> and use mapToDouble to get the DoubleStream , and then toArray() to get the double[] array.

The final call toArray converts this Stream<double[]> into an array double[][] .

+9
source

First of all, forEach is a terminal statement with a return type of void , so you cannot use

 stream().forEach(...).toArray(); // ^void returned here, and void doesn't have `toArray` method 

You need to map your data into double[] strings, and then collect them into double[][] , which will lead us to the second problem, since toArray() (from the stream of objects) returns an array of Object[] , which can't be stored in double[][] link. You have to use

 A[] toArray(IntFunction<A[]> generator) 

which will return the correct data type, so you can use

 toArray(size -> new double[size][]) 

or its shorter version

 toArray(double[][]::new) 

Here is what your code looks like:

 double[][] doubleArray = Arrays.stream(intArray) .map( pArray -> Arrays .stream(pArray) .mapToDouble(d -> d.doubleValue()) .toArray() ).toArray(double[][]::new); //which is equivalent of // ).toArray(size -> new double[size][]); //---[Test]--- for (double[] row : doubleArray){ System.out.println(Arrays.toString(row)); } 

Output:

 [1.0, 2.0, 3.0] [4.0, 5.0, 6.0] [7.0, 8.0, 9.0] 
+3
source

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


All Articles