英文:
How to fill matrix using Stream?
问题
我想学习一些Java中的函数式编程和流操作,这里是我想要接收的矩阵:
Integer[][] availableValues = new Integer[][]{{1,2,3},{1,2,3},{1,2,3},{1,2,3}};
是否有办法使用流来填充这个矩阵,但使用给定的值?(伪代码)
for (数组 在 矩阵中)
for (值 在 数组中)
for (在范围(1,4)之间的下一个值)
值 = 介于1和4之间的下一个值
是否有办法在矩阵中的每个数组中使用流将值从1填充到X?
类似于 Arrays.stream(availableValues).map(x -> IntStream.range(1, 10).forEach(i -> x = i));
但这显然行不通。
英文:
I want to learn some functional programing and streams in Java, here is the matrix that I want to receive:
Integer[][] availableValues = new Integer[][]{{1,2,3},{1,2,3},{1,2,3},{1,2,3}};
Is there any way to fill this matrix with given values but using Streams? (pseudo code)
for array in matrix
for value in array
for range(1,4)
value = next value between 1 and 4
Is there any way to put values from 1 to X in every array in matrix using Streams?
Something like Arrays.stream(availableValues).map(x->IntStream.range(1,10).forEach(i -> x = i));
but it's obviously not working.
答案1
得分: 2
尝试这个:
- 你想要创建4个大小为3的数组的数组,每个数组包含1、2、3。
- 映射的内部流创建其中一个数组。
- 外部流执行这个操作4次,并创建一个包含这些数组的数组。
int[][] v = IntStream.range(1, 5)
.mapToObj(a -> IntStream.range(1, 4).toArray())
.toArray(int[][]::new);
for (int[] arr : v) {
System.out.println(Arrays.toString(arr));
}
输出结果:
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
英文:
Try this:
- You want to create 4 arrays of arrays of size 3 that each contain 1,2,3.
- the mapped inner stream creates one of those arrays.
- the outer stream does that 4 times and creates an array of those arrays.
int[][] v = IntStream.range(1, 5)
.mapToObj(a -> IntStream.range(1, 4).toArray())
.toArray(int[][]::new);
for (int[] arr : v) {
System.out.println(Arrays.toString(arr));
}
Prints
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
</details>
# 答案2
**得分**: 0
这应该是这样的:
```java
int[][] arr = IntStream.range(0, 4)
.mapToObj(i -> IntStream.range(1, 4).toArray())
.collect(Collectors.toList()).toArray(int[][]::new);
Arrays.stream(arr).forEach(a -> System.out.println(Arrays.toString(a)));
输出:
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
英文:
It should be like this:
int[][] arr = IntStream.range(0, 4)
.mapToObj(i -> IntStream.range(1, 4).toArray())
.collect(Collectors.toList()).toArray(int[][]::new);
Arrays.stream(arr).forEach(a -> System.out.println(Arrays.toString(a)));
output
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论