迭代和过滤数组 2D Java 8

Iterate And Filter Array 2D Java 8

我有一个这样的数组:

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();

和像这样的二维数组:

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++;
    }
}

如何获得 java 8 或更高的矩阵中大于 x 的元素数?

您可以使用 flatMapToInt 创建矩阵的 IntStream,然后像之前一样使用 filtercount :

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

这是一种解决方法:

long count = Arrays.stream(matrix_example)
                   .mapToLong(a -> Arrays.stream(a).filter(x -> x > 5).count()).sum();
  • 通过 Arrays.stream
  • matrix_example 创建流
  • 通过mapToLong
  • 将每个数组映射到给定元素大于5的次数
  • 然后我们将所有这些金额加起来通过 sum
  • 得到计数