java 8 bucle anidado con la corriente

plomo:

Tengo un bucle para iterar a través de una Integer [][]map. Actualmente es la siguiente:

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

En lugar de matriz 2D, supongamos que tengo List<List<Integer>> maps2d. ¿Cómo iba a hacer eso con las corrientes?

Hasta ahora tengo este:

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

                               }
      )
);

¿Es correcto hasta ahora? En caso afirmativo, ¿Cómo cuento iy jcon el fin de crear el new Point(i,j)y añadirlo a q?

repollo:

Si realmente desea utilizar corrientes para el mismo propósito a continuación, una opción es utilizar anidados IntStreams para iterar sobre los índices. Como ejemplo:

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

En lo personal, no me parece que tremendamente legible. Nota Puede seguir utilizando bucles for anidados con su lista, similar a la solución actual:

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

Supongo que te gusta

Origin http://10.200.1.11:23101/article/api/json?id=440814&siteId=1
Recomendado
Clasificación