325

I want to verify whether a collection is empty and null. Could anyone please let me know the best practice.

Currently, I am checking as below:

if (null == sampleMap || sampleMap.isEmpty()) {
  // do something
} 
else {
  // do something else
}
Naman
  • 27,789
  • 26
  • 218
  • 353
srk
  • 3,606
  • 2
  • 18
  • 23
  • 21
    Aside from anything else, think about *why* you use `null == sampleMap` rather than `sampleMap == null`. Most people find the latter more readable - the former is a holdover from other languages. – Jon Skeet Oct 04 '12 at 06:03
  • 9
    By the way, null collection is bad. If possible, make it empty collection instead. `See Effective Java: Item 43 - Return empty arrays or collections, not nulls.` – 卢声远 Shengyuan Lu Dec 23 '15 at 04:56
  • 1
    @JonSkeet people use null == sampleMap in case they write = instead of ==. if you use sampleMap == null, when you forget one =, it becomes sampleMap = null, which will not raise error thus writing it the other way helps the developer see it – Uri Loya Nov 14 '19 at 14:39
  • 3
    @UriLoya: If you write `if (null = sampleMap)` in Java you'll get a compilation error. That's precisely the point of my first comment. The "reason" for it is language-specific, but has been propagated to other languages despite the readability penalty because people haven't considered *why* they're doing that. – Jon Skeet Nov 14 '19 at 14:41
  • You can use CollectionUtils class which is present in org.apache.commons.collections4.CollectionUtils package. There have many utility methods to find empty or null. – vikash Mar 18 '20 at 10:14

10 Answers10

489

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.

Marc Bannout
  • 388
  • 4
  • 15
Jalayn
  • 8,934
  • 5
  • 34
  • 51
90

That is the best way to check it. You could write a helper method to do it:

public static boolean isNullOrEmpty( final Collection< ? > c ) {
    return c == null || c.isEmpty();
}

public static boolean isNullOrEmpty( final Map< ?, ? > m ) {
    return m == null || m.isEmpty();
}
icza
  • 389,944
  • 63
  • 907
  • 827
  • 1
    There must be a similar function for `Map>` as well. – Luiggi Mendoza Oct 04 '12 at 05:59
  • 2
    Sure, you can add one for maps too, but the title stated collection. – icza Oct 04 '12 at 06:06
  • 2
    I don't understand if m is null then .isEmpty() will cause NullPointerException rigth? otherwise, if the left side (m==null) is true then the remaining will not be checked – Ismail Sahin Jul 29 '16 at 08:46
  • 7
    @ismail The `||` operator is a short-circuit operator, meaning if the left operand is `true`, it won't evaluate the right operand. So if `m == null`, then `m.isEmpty()` will not be called (not needed, the result is `true`). – icza Jul 29 '16 at 09:05
64

If you use Spring frameworks, then you can use CollectionUtils to check against both Collections (List, Array) and Map etc.

if(CollectionUtils.isEmpty(...)) {...}
Saorikido
  • 2,173
  • 2
  • 26
  • 37
  • 2
    BTW, spring's CollectionUtils there is comment about... "Miscellaneous collection utility methods. Mainly for internal use within the framework." So, I'm not sure using this method :-) – coverboy May 10 '23 at 04:57
23

When you use spring then you can use

boolean isNullOrEmpty = org.springframework.util.ObjectUtils.isEmpty(obj);

where obj is any [map,collection,array,aything...]

otherwise: the code is:

public static boolean isEmpty(Object[] array) {
    return (array == null || array.length == 0);
}

public static boolean isEmpty(Object obj) {
    if (obj == null) {
        return true;
    }

    if (obj.getClass().isArray()) {
        return Array.getLength(obj) == 0;
    }
    if (obj instanceof CharSequence) {
        return ((CharSequence) obj).length() == 0;
    }
    if (obj instanceof Collection) {
        return ((Collection) obj).isEmpty();
    }
    if (obj instanceof Map) {
        return ((Map) obj).isEmpty();
    }

    // else
    return false;
}

for String best is:

boolean isNullOrEmpty = (str==null || str.trim().isEmpty());
22

Personally, I prefer to use empty collections instead of null and have the algorithms work in a way that for the algorithm it does not matter if the collection is empty or not.

tehlexx
  • 2,821
  • 16
  • 29
11

We'll check a Collection object is empty, null or not. these all methods which are given below, are present in org.apache.commons.collections4.CollectionUtils package.

Check on List or set type of collection Objects.

CollectionUtils.isEmpty(listObject);
CollectionUtils.isNotEmpty(listObject);

Check on Map type of Objects.

MapUtils.isEmpty(mapObject);
MapUtils.isNotEmpty(mapObject);

The return type of all methods is boolean.

vikash
  • 381
  • 2
  • 11
  • CollectionUtils.isEmpty(listObject); this ain't working for all collections. i have tried with set and it is not working. – saravana kumar ramasamy Dec 22 '21 at 06:58
  • The core part to check any collection object that is null, empty or not, is collection == null || collection.isEmpty() Internally so you can use this. – vikash Dec 29 '21 at 07:23
8

You can use org.apache.commons.lang.Validate's "notEmpty" method:

Validate.notEmpty(myCollection) -> Validate that the specified argument collection is neither null nor a size of zero (no elements); otherwise throwing an exception.

Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
  • This is a good alternative for parameter validations as the `CollectionUtils.isEmpty(...)` is not present in older versions of the library. However, the `Validate.notEmpty(...)` method throws an exception when empty. In @srk scenario won't work if we believe using exception is bad for flow control. https://web.archive.org/web/20140430044213/http://c2.com/cgi-bin/wiki?DontUseExceptionsForFlowControl – Jesfre Jul 22 '22 at 20:25
3

If you need to check for null, that is the way. However, if you have control on this, just return empty collection, whenever you can, and check only for empty later on.

This thread is about the same thing with C#, but the principles applies equally well to java. Like mentioned there, null should be returned only if

  • null might mean something more specific;
  • your API (contract) might force you to return null.
Community
  • 1
  • 1
eis
  • 51,991
  • 13
  • 150
  • 199
0

Taking the case you collection is a List, you can simply use this

private boolean collectionIsNotNullAndNotEmpty(List<?> collection) {
    return Objects.nonNull(collection) && !collection.isEmpty();
}
Kevin KOUOMEU
  • 159
  • 1
  • 1
  • 9
-4

For all the collections including map use: isEmpty method which is there on these collection objects. But you have to do a null check before:

Map<String, String> map;

........
if(map!=null && !map.isEmpty())
......
pringi
  • 3,987
  • 5
  • 35
  • 45