用Java初始化带有流的2d数组 [英] Initializing 2d array with streams in Java
本文介绍了用Java初始化带有流的2d数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下课程:
public class MyClass{
//...
public MyClass(int x, int y){
//...
}
}
现在,我需要使用项目初始化2d数组
Now, I need to initialize 2d-array with the items
int rows;
int cols;
//initializing rows and cols
MyClass[][] arr = new MyClass[rows][cols];
//how to initialize arr[x][y] with
//new MyClass(x, y) with streams API
我查看了这个示例,但它在我的案例中不起作用。他们使用一个 IntStream
I looked at this example but it doesn't work in my case. They use a single IntStream
问题: 当然我可以使用嵌套for循环,但我认为它现在是旧式的并且考虑不好。那么如何应用流api并以 Java8
方式启动它?
推荐答案
Streams不太擅长跟踪索引,这是您需要的。所以你可以像@NicolasFilotto那样滥用它们,或者以更简单的方式:
Streams are not very good at keeping track of index, which you need here. So you can abuse them like @NicolasFilotto proposes, or in a simpler way:
MyClass[][] array = new MyClass[rows][cols];
IntStream.range(0, rows)
.forEach(r -> IntStream.range(0, cols)
.forEach(c -> array[r][c] = new MyClass(r, c)));
你甚至可以让它看起来更实用,摆脱 forEach
和变异部分:
You could even make it look more functional and get rid of the forEach
and the mutation part:
MyClass[][] array = IntStream.range(0, rows)
.mapToObj(r -> IntStream.range(0, cols)
.mapToObj(c -> new MyClass(r, c))
.toArray(MyClass[]::new))
.toArray(MyClass[][]::new);
但老实说, for循环不会过时:
But honestly, for loops are not obsolete:
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
array[r][c] = new MyClass(r, c);
}
}
这篇关于用Java初始化带有流的2d数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文