簡體   English   中英

帶有流的java 8嵌套循環

[英]java 8 nested loop with stream

我有一個 for 循環迭代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));
    }
}        

而不是二維數組,假設我有List<List<Integer>> maps2d 我將如何使用流來做到這一點?

到目前為止,我得到了這個:

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

                               }
      )
);

到目前為止它是正確的嗎? 如果是,我如何計算ij以創建new Point(i,j)並將其添加到q

如果您真的想將流用於相同的目的,那么一種選擇是使用嵌套的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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM