IAmYourFaja IAmYourFaja - 2 months ago 27
Java Question

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
:


  • 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.

Answer Source
 keys.contains(null) || keys.contains("")

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