Tuesday 21 April 2020

How to check whether a map is null or empty?

Following snippet return true if the map is null or empty.

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

App.java
package com.sample.app;

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

public class App {

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

	public static void main(String args[]) {
		System.out.println("Is map empty : " + isMapNullOrEmpty(null));
		System.out.println("Is map empty : " + isMapNullOrEmpty(Collections.EMPTY_MAP));

		Map<Integer, String> map = new HashMap<>();
		map.put(1, "Krishna");

		System.out.println("Is map empty : " + isMapNullOrEmpty(map));
	}

}

Output
Is map empty : true
Is map empty : true
Is map empty : false

You may like

No comments:

Post a Comment