A Method to Check If a Collection or Map Is Empty or Null

Best practice to validate null and empty collection in Java

If you use the Apache Commons Collections library in your project, you may use the CollectionUtils.isEmpty and MapUtils.isEmpty() methods which respectively check if a collection or a map is empty or null (i.e. they are "null-safe").

The code behind these methods is more or less what user @icza has written in his answer.

Regardless of what you do, remember that the less code you write, the less code you need to test as the complexity of your code decreases.

A method to check if a Collection or Map is empty or null?

Your isCollectionMapNullOrEmpty compiles and works, but not the way you intended.

<T extends Collection, Map>

You've declared two type variables, T and Map, where T must be a Collection. The type variable Map has nothing to do with the interface Map, and is in fact not even used. (Also, you used the raw Collection interface here.) You are passing aList which is a Collection, so it compiles. However, aMap is not a Collection, so the compilation fails passing in a Map.

It looks like you wanted T to be either a Collection or a Map. But Java's generics don't work that way; you can't declare a type parameter to be one thing or another thing.

(As an aside, you can say one thing and another thing: T extends Collection & Map, or without raw types, T extends Collection<?> & Map<?, ?>, but I'm not aware of any classes that implement both interfaces.)

You can have two overloaded methods, one for a Collection and one for a Map, that will perform the same functionality. Here, I've taken advantage of short-circuiting to combine the statements:

protected static boolean isCollectionMapNullOrEmpty(final Collection<?> c) {
return c == null || c.isEmpty();
protected static boolean isCollectionMapNullOrEmpty(final Map<?, ?> m) {
return m == null || m.isEmpty();

Both methods have the same exact code, but because there is no super-interface declaring isEmpty, this appears to be as good as it gets.

Checking if a collection is empty in Java: which is the best method?

You should absolutely use isEmpty(). Computing the size() of an arbitrary list could be expensive. Even validating whether it has any elements can be expensive, of course, but there's no optimization for size() which can't also make isEmpty() faster, whereas the reverse is not the case.

For example, suppose you had a linked list structure which didn't cache the size (whereas LinkedList<E> does). Then size() would become an O(N) operation, whereas isEmpty() would still be O(1).

Additionally of course, using isEmpty() states what you're actually interested in more clearly.

Check if Java object is Collection, Array or String and empty

As mentioned in deHaar's answer, the code can be improved by using if-return combinations.

You should however generalize your code a bit more, e.g. support all array types, not just string arrays, and support all collection types, not just lists.

Similarly, String implements an interface named CharSequence, so support that instead. That way the code will support classes like StringBuilder and StringBuffer too.

public static boolean isEmpty(Object value) {
if (value == null)
return true;
if (value instanceof CharSequence) // String, StringBuilder, StringBuffer, ...
return ((CharSequence) value).isEmpty();
if (value instanceof Collection) // List, Set, Queue, Deque, ...
return ((Collection<?>) value).isEmpty();
if (value instanceof Map)
return ((Map<?,?>) value).isEmpty();
if (value.getClass().isArray()) // All array types
return (Array.getLength(value) == 0);
return false;

Code was modified to to use pure built-in methods, i.e. to not rely on ArrayUtils.

UPDATED: Added support for primitive arrays.

The above implementation is a close match to the JSP EL empty operator:

The empty operator is a prefix operator that can be used to determine if a value is null or empty.

To evaluate empty A

  • If A is null, return true
  • Otherwise, if A is the empty string, then return true
  • Otherwise, if A is an empty array, then return true
  • Otherwise, if A is an empty Map, return true
  • Otherwise, if A is an empty Collection, return true
  • Otherwise return false

How to check if a Map or Set is empty?

You use its size property. Both Maps and Sets have it (here and here).

const populatedSet = new Set(['foo']);console.log(populatedSet.size);  // 1
const populatedMap = new Map([['foo', 1]]);console.log(populatedMap.size); // 1

Java 8 nested null check for a string in a map in a list

You could use a long chain of Optional and Stream operations to transform the input step by step into the output. Something like this (untested):

String[] test = Optional.ofNullable(checkList)
.map(m -> m.get("filename"))
.filter(f -> !f.trim().isEmpty())
.map(f -> f.split("_"))

I'd strongly encourage you to stop using null lists and maps. It's a lot better to use empty collections rather than null collections, that way you don't have to have null checks all over the place. Furthermore, don't allow empty or blank strings into your collections; filter them out or replace them with null early, as soon as you're converting user input into in-memory objects. You don't want to have to insert calls to trim() and isBlank() and the like all over the place.

If you did that you could simplify to:

String[] test = checkList.stream()
.map(m -> m.get("filename"))
.map(f -> f.split("_"))

Much nicer, no?

Related Topics

Leave a reply