How to determine if a list of string contains null or empty elements

Viewed 98046

In Java, I have the following method:

public String normalizeList(List<String> keys) {
    // ...
}

I want to check that keys:

  • Is not null itself; and
  • Is not empty (size() == 0); and
  • Does not have any String elements that are null; and
  • Does not have any String elements that are empty ("")

This is a utility method that will go in a "commons"-style JAR (the class wil be something like DataUtils). Here is what I have, but I believe its incorrect:

public String normalize(List<String> keys) {
    if(keys == null || keys.size() == 0 || keys.contains(null) || keys.contains(""))
        throw new IllegalArgumentException("Bad!");

    // Rest of method...
}

I believe the last 2 checks for keys.contains(null) and keys.contains("") are incorrect and will likely thrown runtime exceptions. I know I can just loop through the list inside the if statement, and check for nulls/empties there, but I'm looking for a more elegant solution if it exists.

8 Answers

With java 8 you can do:

public String normalizeList(List<String> keys) {
    boolean bad = keys.stream().anyMatch(s -> (s == null || s.equals("")));
    if(bad) {
        //... do whatever you want to do
    }
}

Aniket gave a really good answer for this as a comment:

if( keys.stream().anyMatch(String::isBlank) ) { .... String::isBlank is since Java11. – 
Aniket Sahrawat
Apr 6, 2019 at 2:30

So to tweak your original solution using Aniket's comment:

public String normalize(List<String> keys) {
    if(keys == null || keys.size() == 0  || keys.stream().anyMatch(String::isBlank)){
        throw new IllegalArgumentException("Bad!");
    }

    // Rest of method...
}

if you can use org.springframework.util.CollectionUtils you can apply this

if(CollectionUtils.isEmpty(coll) || CollectionUtils.containsInstance(coll, null)) {
        // throw ...;
}

It does not throw NullPointerException for immutable collection as List.of().

Related