4

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?

0

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.