Iterate And Filter Array 2D Java 8

Sergio.Ramirez :

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?

Naman :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=93707&siteId=1