带有流的java 8嵌套循环

5 java java-8 java-stream

我有一个 for 循环迭代 a Integer [][]map。目前是这样的:

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));
    }
}        
Run Code Online (Sandbox Code Playgroud)

而不是二维数组,假设我有List<List<Integer>> maps2d. 我将如何使用流来做到这一点?

到目前为止,我得到了这个:

maps2d.stream()
      .forEach(maps1d -> maps1d.stream()
                               .filter(u -> u == 1)
                               .forEach(u -> {

                               }
      )
);
Run Code Online (Sandbox Code Playgroud)

到目前为止它是正确的吗?如果是,我如何计算ij创建new Point(i,j)并将其添加到q

Sla*_*law 4

如果您确实想将流用于相同目的,那么一种选择是使用嵌套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>
}
Run Code Online (Sandbox Code Playgroud)

就我个人而言,我不认为它具有很强的可读性。请注意,您仍然可以在列表中使用嵌套 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;
}
Run Code Online (Sandbox Code Playgroud)