Stream from two dimensional array in java

2019-03-12 03:13发布

问题:

I am trying to get an IntStream out of an n dimensional int arrays. Is there a nice API way to do it? I know the concatenate method for two streams.

回答1:

Assuming you want to process array of array sequentially in row-major approach, this should work:

int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
IntStream stream = Arrays.stream(arr).flatMapToInt(x -> Arrays.stream(x));

First it invokes the Arrays.stream(T[]) method, where T is inferred as int[], to get a Stream<int[]>, and then Stream#flatMapToInt() method maps each int[] element to an IntStream using Arrays.stream(int[]) method.



回答2:

To further expand on Rohit's answer, a method reference can be used to slightly shorten the amount of code required:

int[][] arr = { {1, 2, 3}, 
                {4, 5, 6},
                {7, 8, 9} };

IntStream stream = Arrays.stream(arr).flatMapToInt(Arrays::stream);


回答3:

To process the elements only, use flatMap as in Rohit's answer.

To process the elements with their indices, you may use IntStream.range as follows.

import java.util.stream.IntStream;
import static java.util.stream.IntStream.range;

public class StackOverflowTest {
    public static void main(String... args) {
        int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        // Map the two dimensional array with indices.
        final IntStream intStream = range(0, arr.length).flatMap(row -> range(0, arr[row].length).map(col -> {
            final int element = arr[row][col];
            // E.g. multiply elements in odd numbered rows and columns by two.
            return row % 2 == 1 || col % 2 == 1 ? element * 2 : element;
        }));
        // Prints "1 4 3 8 10 12 7 16 9 ".
        intStream.forEachOrdered(n -> System.out.print(n + " "));
    }
}