Check if Map is Null or Empty in Java

In this short article, we will discuss how to check if the Map is empty or null in Java. Let's create a standard utility method to check if the Map is empty or null in Java.
Learn Java collections framework in-depth at Java Collections Framework in Depth

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

  1. isNullOrEmptyMap(Map, ?> map) - Return true if the supplied Map is null or empty. Otherwise, return false.
  2. isNotNullOrEmptyMap(Map, ?> map) - Return true if the supplied Map is not null or not empty. Otherwise, return false.

1. isNullOrEmptyMap() Utility Method

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

2. isNotNullOrEmptyMap() Utility Method

Return true if the supplied Map is not null or not empty. Otherwise, return false.
public static boolean isNotNullOrEmptyMap(Map <? , ?> map) {
    return !isNullOrEmptyMap(map); // this method defined below
}

public static boolean isNullOrEmptyMap(Map <? , ?> map) {
    return (map == null || map.isEmpty());
}

Complete Example

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

import java.util.HashMap;
import java.util.Map;

public class MapNullOrEmptyExample {

    public static void main(String[] args) {

        // return true
        System.out.println(isNullOrEmptyMap(null));
        System.out.println(isNullOrEmptyMap(new HashMap < > ()));

        Map < String, String > map = new HashMap < > ();
        map.put("key1", "value1");
        map.put("key2", "value2");

        // return true
        System.out.println(isNotNullOrEmptyMap(map));

        // return false
        System.out.println(isNullOrEmptyMap(map));

    }


    public static boolean isNullOrEmptyMap(Map << ? , ? > map) {
        return (map == null || map.isEmpty());
    }

    public static boolean isNotNullOrEmptyMap(Map << ? , ? > map) {
        return !isNullOrEmptyMap(map);
    }

}
Output:
true
true
true
false

Related Java Utility Methods or Classes

Collections Examples

Comments