我有一个Integer [][]map
上的for循环。
当前是这样的:
for(int i = 0; i < rows; i++) {
for(int j = 0; j < columns; j++) {
if(map[i][j] == 1)
q.add(new Point(i,j));
}
}
假设我有List<List<Integer>> maps2d
而不是2d数组。
我将如何使用流?
到目前为止,我知道了:
maps2d.stream()
.forEach(maps1d -> maps1d.stream()
.filter(u -> u == 1)
.forEach(u -> {
}
)
);
到目前为止是否正确?
如果是,如何计算i
和j
以创建new Point(i,j)
并将其添加到q
中?
答案 0 :(得分:5)
如果您真的想将流用于同一目的,那么一种选择是使用嵌套的IntStream
来遍历索引。例如:
public static List<Point> foo(List<List<Integer>> map) {
return IntStream.range(0, map.size()) // IntStream
.mapToObj(
i ->
IntStream.range(0, map.get(i).size())
.filter(j -> map.get(i).get(j) == 1)
.mapToObj(j -> new Point(i, j))) // Stream<Stream<Point>>
.flatMap(Function.identity()) // Stream<Point>
.collect(Collectors.toList()); // List<Point>
}
就我个人而言,我认为它的可读性不强。请注意,您仍然可以对列表使用嵌套的for循环,类似于您当前的解决方案:
public static List<Point> foo(List<List<Integer>> map) {
List<Point> result = new ArrayList<>();
for (int i = 0; i < map.size(); i++) {
List<Integer> inner = map.get(i);
for (int j = 0; j < inner.size(); j++) {
if (inner.get(j) == 1) {
result.add(new Point(i, j));
}
}
}
return result;
}