java怎么判断数组有几个孔

Java 中判断数组空值个数的方法有:1. 使用 null 查询;2. 使用 Arrays.stream() 和 filter();3. 使用 int[] 和 0 初始化;4. 使用 Optional 和 isPresent();5. 使用 Guava 的 Iterables.filter()。

如何判断 Java 数组中有几个空值

在 Java 中,可以通过以下方法判断数组中有多少个空值:

1. 使用 null 查询

int countNullValues = 0;
for (Object element : array) {
    if (element == null) {
        countNullValues++;
    }
}

2. 使用 Arrays.stream()filter()

int countNullValues = (int) Arrays.stream(array)
    .filter(Objects::isNull)
    .count();

3. 使用 int[]0 初始化

int[] countNullValues = new int[1];
Arrays.stream(array)
    .forEach(element -> {
        if (element == null) {
            countNullValues[0]++;
        }
    });

4. 使用 OptionalisPresent()

int countNullValues = 0;
for (Object element : array) {
    Optional optionalElement = Optional.ofNullable(element);
    if (!optionalElement.isPresent()) {
        countNullValues++;
    }
}

5. 使用 Guava 的 Iterables.size(Iterables.filter(array, Predicates.isNull()))

import co

m.google.common.collect.Iterables; import com.google.common.base.Predicates; int countNullValues = Iterables.size(Iterables.filter(array, Predicates.isNull()));