简体   繁体   English

如何将Java 8 Stream转换为二维数组?

[英]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. 我正在尝试将基于地图的Stream转换为二维数组。 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. 当我执行上面的代码时,我按预期填充了我的Float数组。 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? 你能告诉我如何使用Java 8流完成这项任务吗? Thanks in advance! 提前致谢!

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. 如果您查看<A> A[] toArray(IntFunction<A[]> generator) ,您会看到它将Stream<A>转换为A[] ,这是A元素的一维数组。 So in order for it to create a 2D array, the elements of the Stream must be arrays. 因此,为了创建2D数组, Stream的元素必须是数组。

Therefore you can create a 2D array if you first map the elements of your Stream to a 1D array and then call toArray : 因此,如果首先将Stream的元素map到1D数组,然后调用toArray ,则可以创建2D数组:

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

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. 这就像你期望的那样创建一个2D数组。

Note: By the comment 1) you have to replace YourKeyClass with the class containing the method getPrice() returning a Float object. 注意:通过注释1)你必须用包含方法getPrice()的类替换YourKeyClass ,返回一个Float对象。


An alternative is also to use .keySet() instead of .entrySet() : 另一种方法是使用.keySet()而不是.entrySet()

Float[][] array = map.keySet().stream()
    .map(YourKeyClass::getPrice)
    .map(price -> new Float[]{price})
    .toArray(Float[][]::new);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM