在 Java 8 版本之前,我们可以像下面这样使用 for 循环来初始化一个二维数组。我如何使用 lambda 表达式在 JDK 1.8 中执行以下操作?
int[][] board = new int[3][3];
int v = 1;
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = v;
v++;
System.out.println(v);
}
}
System.out.println(Arrays.deepToString(board));
基本上,我正在寻找如下所示的数组
[[1,6],[2,7],[3,8],[4,9]]
最佳答案
我强烈建议您坚持使用 for-loop
用于初始化具有原始值的数组。在多维数组的情况下,我的建议更强。
不过,方法是这样的:
int a = 4; // Number of outer array elements
int b = 2; // Number of inner array elements
int[][] board = IntStream
.range(0, a) // iterate 0..3
.mapToObj(i -> IntStream.range(0, b) // for each iteratoe 0..1
.map(j -> 1 + (i + (a + 1) * j)) // calculate the value
.toArray()) // compose the inner array
.toArray(int[][]::new); // compose the outer array
请注意 IntStream
能够创建基元数组,因为它是基元 int 值元素的序列。它的方法 IntStream::toArray
回复 int[]
.
自int[]
以来,外部数组的组成有点棘手。不再是一个原始值,而是一个数组本身。需要使用一种方法 IntStream::mapToObj
哪些 map int
到一个对象 - 然后是 Stream<int[]>
返回和方法 Stream::toArray(IntFunction<A[]> generator)
必须使用参数转换为数组,因为您无法转换 Object[]
至 int[][]
.
传递的参数很简单。 int[][]::new
与 i -> new int[a][b]
没什么不同.
关于java - 如何在java 8中初始化二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52048349/