如何使用Java8流生成2D int数组?
我正在尝试使用Java8流生成如何使用Java8流生成2D int数组?,java,java-8,java-stream,Java,Java 8,Java Stream,我正在尝试使用Java8流生成int[][] 这就是我到目前为止所做的: objects.parallelStream() .map(o -> o.getPropertyOnes() .parallelStream() .map(t-> t.getIndex()) //<-- getIndex() returns int .mapTo
int[][]
这就是我到目前为止所做的:
objects.parallelStream()
.map(o -> o.getPropertyOnes()
.parallelStream()
.map(t-> t.getIndex()) //<-- getIndex() returns int
.mapToInt(i -> i)
.toArray()) //<-- here I have a Stream<int[]>
.toArray(); //lost here
objects.parallelStream()
.map(o->o.getPropertyOnes()
.parallelStream()
.map(t->t.getIndex())//i)
.toArray())/首先,您可以将map().mapToInt()
简化为mapToInt(t->t.getIndex())
(也许您应该使用类似::getIndex
的方法引用)
正如您所说,在map
阶段之后有Stream
。然后您只需要提供一个数组生成器函数,如:
int[][] array = Stream.of(1, 2, 3, 4)
.map(i -> IntStream.range(0, i).toArray())
.toArray(int[][]::new);
输出:
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
您需要一种方法来帮助我们通过IntFunction
函数指定返回类型:
int[][] a = Stream.of(new int[]{1, 2, 3}, new int[]{4, 5, 6}).toArray(int[][]::new);
而不是,它返回Object[]
,而不管流中的传入类型如何(在内部调用toArray(Object[]::new)
:
如果您感兴趣,在幕后,所有这些都具有以下外观:
从上一阶段的管道
中形成节点
[在我们的例子中是阵列节点
](用于保持元素有序序列的不可变容器)李>
使用节点大小(node.count()
)计算数组大小李>
通过我们的IntFunction
生成器(i->new int[i][
或简单地int[]]::new
)获取具有所需长度的新空数组李>
从节点复制到此数组并返回后者
如果要生成n X n的序列号的2D数组,其中n在度数中
int n = 4;
System.out.println(Arrays.deepToString(IntStream.rangeClosed(0, n - 1)
.boxed().map(x -> IntStream.rangeClosed(x * n + 1, (x + 1) * n)
.boxed().toArray()).toArray()));
Output: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
您正在寻找flatMap吗?@Eugene No,不想展平集合,而是想创建一个2d int数组。如何将流转换为int[]]?你能举个例子吗?更好地向我们展示您的输入和所需的输出,不清楚您想要做什么您必须使用toArray(int[]]::new)
。而不是两步.map(t->t.getIndex()).mapToInt(i->i)
,您可以直接使用mapToInt(t->t.getIndex())
。谢谢您的回答。我还需要等几分钟才能接受。不过有一个问题,我试着对内部映射执行toArray(int[]::new)
,即代替.map(t->t.getIndex()).mapToInt(I->I.toArray()
,尝试了以下操作:.map(t->t.getIndex()).toArray(int[]:new)
。知道为什么吗?@SayanPal你有一个流
这个不能存储在int[]
中Stream::mapToInt
返回一个IntStream
,它提供了一个toArray
方法,该方法返回一个int[]
。这正是你需要的。
int n = 4;
System.out.println(Arrays.deepToString(IntStream.rangeClosed(0, n - 1)
.boxed().map(x -> IntStream.rangeClosed(x * n + 1, (x + 1) * n)
.boxed().toArray()).toArray()));
Output: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]