简体   繁体   中英

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?

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

Here's one way to go about it:

long count = Arrays.stream(matrix_example)
                   .mapToLong(a -> Arrays.stream(a).filter(x -> x > 5).count()).sum();
  • creates a stream from matrix_example via Arrays.stream
  • maps each array to the number of times a given element is greater than 5 via mapToLong
  • then we take all those amounts and sum them up to get the count via sum

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM