Java Utility Library

Java Collections - unmodifiableMap() Method



The java.util.Collections.unmodifiableMap() method returns an unmodifiable view of the specified map.

Syntax

public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)

Here, K and V are the type of key and value respectively maintained by the map.


Parameters

m Specify the map for which an unmodifiable view is to be returned.

Return Value

Returns an unmodifiable view of the specified map.

Exception

NA.

Example:

In the example below, the java.util.Collections.unmodifiableMap() method returns an unmodifiable view of the given map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a Map object
    Map<Integer, String> MyMap = new HashMap<Integer, String>();

    //populating MyMap
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");

    //printing the map
    System.out.println("MyMap contains: " + MyMap); 

    //creating an unmodifiable view of the map
    Map NewMap = Collections.unmodifiableMap(MyMap);

    //printing the unmodifiable map
    System.out.println("NewMap contains: " + NewMap); 

    //trying to modify the NewMap
    NewMap.put(104, "Ramesh");    
  }
}

The output of the above code will be:

MyMap contains: {101=John, 102=Marry, 103=Kim}
NewMap contains: {101=John, 102=Marry, 103=Kim}

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.Collections$UnmodifiableMap.put(Collections.java:1457)
    at MyClass.main(MyClass.java:23)

❮ Java.util - Collections