Check if Collection is Empty or Null in Java


In this short article, we will discuss how to check if the collection is empty or null in Java.

Let's create a standard utility method to check if the collection is empty or null in Java.

Check if Collection is Empty or Null in Java - Utility Methods

  1. isEmptyOrNull(Collection<?> collection) - Return true if the supplied Collection is null or empty. Otherwise, return false.
  2. isNotEmptyOrNull(Collection<?> collection) - Return true if the supplied Collection is not null or not empty. Otherwise, return false.

1. isEmptyOrNull(Collection<?> collection)

Return true if the supplied Collection is null or empty. Otherwise, return false.
 public static boolean isEmptyOrNull(Collection << ? > collection) {
        return (collection == null || collection.isEmpty());
 }

2. isNotEmptyOrNull(Collection<?> collection)

Return true if the supplied Collection is not null or not empty. Otherwise, return false.
    public static boolean isNotEmptyOrNull(Collection << ? > collection) {
        return !isEmptyOrNull(collection);
    }

Complete Example

Here is a complete example to test the above utility methods
package net.javaguides.lang;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class CollectionNullOrEmptyExample {

    public static void main(String[] args) {

        // return true if collection is null or empty
        System.out.println(isEmptyOrNull(null));
        System.out.println(isEmptyOrNull(new ArrayList < > ()));
        System.out.println(isEmptyOrNull(new LinkedList < > ()));
        System.out.println(isEmptyOrNull(new HashSet < > ()));

        // return false if collection is not empty or null
        System.out.println(isNotEmptyOrNull(new ArrayList < > ()));
        System.out.println(isNotEmptyOrNull(new LinkedList < > ()));
        System.out.println(isNotEmptyOrNull(new HashSet < > ()));

        // return false if collection is not empty or null
        List < String > list = new ArrayList < String > ();
        list.add("ABC");
        System.out.println(isNotEmptyOrNull(list));

        List < String > list1 = new LinkedList < > ();
        list1.add("ABC");
        System.out.println(isNotEmptyOrNull(list1));

        Set < String > set = new HashSet < String > ();
        set.add("ABC");
        System.out.println(isNotEmptyOrNull(set));
    }

    public static boolean isEmptyOrNull(Collection << ? > collection) {
        return (collection == null || collection.isEmpty());
    }

    public static boolean isNotEmptyOrNull(Collection << ? > collection) {
        return !isEmptyOrNull(collection);
    }
}
Output:
true
true
true
true
false
false
false
true
true
true

Related Articles


Comments