Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Java 8 Stream into a two dimensional array?

I’m trying to convert a map based Stream into a two-dimensional array. I have figured out how to store it in a one dimensional array. Here is working code snippet:

Float[] floatArray = map.entrySet()
                        .stream()
                        .map(key -> key.getKey().getPrice())
                        .toArray(size -> new Float[size]);

When I execute the above code, I get my Float array populated as expected. Now I need to extend this to a two-dimensional array where I need to store the result in first dimension of a 2d array along these lines:

Float[][1] floatArray = map.entrySet()
                           .stream()
                           .map(key -> key.getKey().getPrice())
                           .toArray(size -> new Float[size][1]);

The code above does not work. Can you please let me know how to accomplish this task with Java 8 streams? Thanks in advance!

like image 894
MazS Avatar asked Nov 20 '17 17:11

MazS


People also ask

How do I turn an array into a 2d array?

Use reshape() Function to Transform 1d Array to 2d Array The number of components within every dimension defines the form of the array. We may add or delete parameters or adjust the number of items within every dimension by using reshaping.

How do you collect an array from a stream?

Collect Stream to Integer array If you want to convert to Integer array, you can use IntStream to do it. You can call toArray() on IntStream and it will simply convert it to int[]. You don't need to pass any argument in this scenario. That's all about converting a Java stream to array in java.


2 Answers

You can make use of the following:

Float[][] array = map.entrySet()
    .stream()
    .map(Map.Entry::getKey)
    .map(YourKeyClass::getPrice) // 1)
    .map(price -> new Float[]{ price })
    .toArray(Float[][]::new);

Which creates a 2D array just like you expected.

Note: By the comment 1) you have to replace YourKeyClass with the class containing the method getPrice() returning a Float object.


An alternative is also to use .keySet() instead of .entrySet():

Float[][] array = map.keySet().stream()
    .map(YourKeyClass::getPrice)
    .map(price -> new Float[]{price})
    .toArray(Float[][]::new);
like image 59
Lino Avatar answered Oct 12 '22 23:10

Lino


If you look at <A> A[] toArray(IntFunction<A[]> generator), you see that it converts a Stream<A> to a A[], which is a 1D array of A elements. So in order for it to create a 2D array, the elements of the Stream must be arrays.

Therefore you can create a 2D array if you first map the elements of your Stream to a 1D array and then call toArray:

Float[][] floatArray = 
    map.entrySet()
       .stream()
       .map(key -> new Float[]{key.getKey().getPrice()})
       .toArray(size -> new Float[size][1]);
like image 29
Eran Avatar answered Oct 13 '22 00:10

Eran