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

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);

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]);