Verifying null collection with null elements inside

My problem is that a collection has a null value, and any "utils" method return that the collection is not empty. There are other "elegant" options?

This code throws a null pointer exception:

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

Upvotes: 0

Views: 300

Answers (1)

Abacus
Abacus

Reputation: 19421

You can check if there are nulls in the collection and/or filter like in the following code:

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

Upvotes: 1

Related Questions