简体   繁体   English

带有流的java 8嵌套循环

[英]java 8 nested loop with stream

I have a for loop iterating over a Integer [][]map .我有一个 for 循环迭代Integer [][]map Currently is like this:目前是这样的:

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));
    }
}        

Instead of 2d array, suppose I have List<List<Integer>> maps2d .而不是二维数组,假设我有List<List<Integer>> maps2d How would I do that with streams?我将如何使用流来做到这一点?

So far I got this:到目前为止,我得到了这个:

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

                               }
      )
);

Is it correct so far?到目前为止它是正确的吗? If yes, how do I count i and j in order to create the new Point(i,j) and add it to q ?如果是,我如何计算ij以创建new Point(i,j)并将其添加到q

If you really want to use streams for the same purpose then one option is to use nested IntStream s to iterate over the indices.如果您真的想将流用于相同的目的,那么一种选择是使用嵌套的IntStream来迭代索引。 As an example:举个例子:

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>
}

Personally, I don't find that tremendously readable.就我个人而言,我不觉得这非常具有可读性。 Note you can still use nested for loops with your list, similar to your current solution:请注意,您仍然可以在列表中使用嵌套的 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM