Ask Your Question

Revision history [back]

click to hide/show revision 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:

  1. We first retrieve the number of rows and columns in the matrix.
  2. We then create an IntStream of row indices using IntStream.range(0, numRows).
  3. For each row i, we create an inner IntStream over the column indices using IntStream.range(0, numCols).
  4. Within the inner IntStream, we use map to retrieve the element at (i, j) in the matrix, where j is the column index.
  5. We flatten the resulting stream of elements using flatMap so that we get a single stream of all the values in the matrix.
  6. Finally, we iterate over the stream using forEach, printing each value to the console.