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 i
y j
con 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 IntStream
s 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;
}