Collections.emptyMap and Collections.emptySet in Java
February 04, 2022
On this page we will learn Collections.emptyMap
and Collections.emptySet
methods.
Collections.emptyMap
The
emptyMap
method returns an immutable empty map.
Map<Integer, String> map = Collections.emptyMap();
The
emptySet
method returns an immutable empty set.
Set<String> s = Collections.emptySet();
Immutable map and set cannot add or remove elements. The use of immutable empty map and set are that if our methods are returning empty map or set, so returning immutable empty map and set ensures that they cannot be changed later.
Example
CollectionsEmptyDemo.javapackage com.concretepage; import java.util.Collections; import java.util.Map; import java.util.Set; public class CollectionsEmptyDemo { int row = getRowFromDB(); //immutable empty Map public Map<Integer,String> getDataInMap(){ Map<Integer,String> map = null; if (row == 0) { map = Collections.emptyMap(); return map; } return map; } //immutable empty Set public Set<String> getDataInSet(){ Set<String> set = null; if (row == 0) { set = Collections.emptySet(); } return set; } private int getRowFromDB() { int cnt = 0; //access DB to calculate rows //returns DB rows return cnt; } }