如何将Java 8 Stream转换为二维数组? [英] How to convert a Java 8 Stream into a two dimensional array?

查看:607
本文介绍了如何将Java 8 Stream转换为二维数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将基于 Stream 的地图转换为二维数组。我已经想出如何将它存储在一维数组中。这是工作代码片段:

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

当我执行上面的代码时,我得到 Float 按预期填充数组。现在我需要将它扩展到一个二维数组,我需要将结果存储在这些行的二维数组的第一维中:

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

上面的代码不起作用。你能告诉我如何使用Java 8流完成这项任务吗?提前致谢!

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

推荐答案

如果你看< A> A [] toArray(IntFunction< A []>生成器),您看到它将 Stream< A> 转换为 A [] ,这是 A 元素的一维数组。因此,为了创建一个2D数组, Stream 的元素必须是数组。

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.

因此你如果您首先 Stream 的元素映射到1D数组,然后调用<$ c,则可以创建2D数组$ c> toArray

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

这篇关于如何将Java 8 Stream转换为二维数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆