1 | initial version |
Assuming that the list of lists is called matrix
, the following code snippet demonstrates how to perform a row-first traversal using IntStream:
int numRows = matrix.size();
int numCols = matrix.get(0).size();
IntStream.range(0, numRows)
.flatMap(i -> IntStream.range(0, numCols).map(j -> matrix.get(i).get(j)))
.forEach(value -> System.out.print(value + " "));
Here's how this works:
IntStream
of row indices using IntStream.range(0, numRows)
.i
, we create an inner IntStream
over the column indices using IntStream.range(0, numCols)
.IntStream
, we use map
to retrieve the element at (i, j)
in the matrix, where j
is the column index.flatMap
so that we get a single stream of all the values in the matrix.forEach
, printing each value to the console.