Search code examples
javajava-8java-streamjava-9

Iterate And Filter Array 2D Java 8


I have an Array like so:

int[] array_example = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
Long count_array = Arrays.stream(array_example)
                      .filter(x -> x>5)
                      .count();

and a 2d array like so:

int[][] matrix_example = {{0, 1, 2, 3, 4}, {5, 6, 7, 8, 9}};
Long count_matrix = 0L;
for(int[] temp: matrix_example){
    for(int x_y: temp){
        if(x_y > 5)
           count_matrix++;
    }
}

How could I obtain the number of elements greater than x of a matrix with java 8 or higher?


Solution

  • You can create an IntStream of the matrix using flatMapToInt then use filter and count as earlier :

    Long count_matrix = Arrays.stream(matrix_example) // Stream<int[]>
            .flatMapToInt(Arrays::stream) // IntStream
            .filter(x_y -> x_y > 5) // filtered as per your 'if'
            .count(); // count of such elements