使用null元素验证null集合

时间:2017-07-06 22:18:59

标签: java

我的问题是集合具有空值,并且任何“utils”方法都返回该集合不为空。还有其他“优雅”的选择吗?

此代码抛出空指针异常:

    public static void main(String[] args) {
    ArrayList<String> strings = new ArrayList<>();
    strings.add(null);

    if(CollectionUtils.isNotEmpty(strings)) {
        for (String s : strings) {
            System.out.println(s.length());
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以检查集合和/或过滤器中是否存在空值,如下面的代码所示:

public static void main(String[] args) {
    List<String> strings = new ArrayList<>();
    strings.add("one");
    strings.add(null);
    strings.add("two");

    // has a null value?
    final boolean hasNulls = strings.stream()
            .anyMatch(Objects::isNull);
    System.out.println("has nulls: " + hasNulls);

    // filter null values
    strings = strings.stream()
            .filter(Objects::nonNull)
            .collect(Collectors.toList());

    System.out.println("filtered: " + strings.toString());
}
相关问题