Java Collections - emptyMap() Method
The java.util.Collections.emptyMap() method returns an empty map (immutable). This map is serializable.
Syntax
public static final <K,V> Map<K,V> emptyMap()
Here, K and V are the type of keys and values, if there were any, in the map.
Parameters
No parameter is required.
Return Value
Returns an empty immutable map.
Exception
NA.
Example:
In the example below, the java.util.Collections.emptyMap() method is used to create an empty immutable map.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating an empty map Map<String, Integer> MyMap = Collections.emptyMap(); //print the content of the map System.out.println("MyMap contains: " + MyMap); //populating the map //as the map is immutable, //the exception is thrown MyMap.put("RED", 1); MyMap.put("BLUE", 2); MyMap.put("GREEN", 3); //print the content of the map System.out.println("MyMap contains: " + MyMap); } }
The output of the above code will be:
MyMap contains: {} Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.AbstractMap.put(AbstractMap.java:209) at MyClass.main(MyClass.java:14)
❮ Java.util - Collections