Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 331
IAmYourFaja Avatar asked Aug 16 '12 17:08

IAmYourFaja


People also ask

How do you check if a list is null or empty?

As other answers here have shown, in order to check if the list is empty you need to get the number of elements in the list ( myList. Count ) or use the LINQ method . Any() which will return true if there are any elements in the list.

How do you check if a list contains null value?

isEmpty() method. A simple solution to check if a list is empty in Java is using the List's isEmpty() method. It returns true if the list contains no elements. To avoid NullPointerException , precede the isEmpty method call with a null check.

How do you check if a string is empty in a list?

Example 2: Using the len() Function Then we used if statement to check if the length of the list is equals to zero or not. If the condition sets to be true then the string is empty. Otherwise the string is not empty.

How do you check if an ArrayList contains null?

v == null : o. equals(v) ). i.e. if o is null , it returns true only if one element is null in the ArrayList. If o is not null , it returns true only if at least one element equal to v.


2 Answers

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

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

like image 61
kosa Avatar answered Sep 22 '22 06:09

kosa


This looks fine to me, the only exceptions you would get from keys.contains(null) and keys.contains("") would be if keys itself was null.

However since you check for that first you know that at this point keys is not null, so no runtime exceptions will occur.

like image 40
NominSim Avatar answered Sep 22 '22 06:09

NominSim