javastringcollections

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


In Java, I have the following method:

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

I want to check that keys:

This is an utility method which will go in a "commons"-style JAR (the class wil be something like DataUtils). Here is what I have, but I believe it's 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.


Solution

  •  keys.contains(null) || keys.contains("")
    

    Doesn't throw any runtime exceptions and results true if your list has either null (or) empty String.