Convert a Map to a Read-Only Map in Java



A read-only map in Java is a type of Map that cannot be modified after it has been created. This means that once the map has been set to be read-only, we cannot add, remove, or update any of the key-value pairs.

Converting a Map to a read only map

We can convert a mutable map to an immutable map, a read-only map using the Collections.unmodifiableMap() method. This method provides a way to make sure that the map cannot be modified once it has been wrapped in this method.

Following are the steps to convert a Map to a read-only map ?

  • Step 1: We create a HashMap and populate it with some key-value pairs.
  • Step 2: We convert the HashMap to a read-only map using Collections.unmodifiableMap().
  • Step 3: We attempt to modify the read-only map, which throws an UnsupportedOperationException.

Let's say the following is our Map ?

Map<String, String>map = new HashMap<String,String>();
map.put("1","A");
map.put("2","B");
map.put("3","C");

Make it read-only using the unmodifiableMap() Method ?

map = Collections.unmodifiableMap(map);

Java program to convert a Map to a read only map

In the following program, we create a 'HashMap' and wrap it with 'Collections.unmodifiableMap()' to create a read-only map. When attempting to modify the read-only map, an 'UnsupportedOperationException' is caught and handled, showcasing the immutability feature.

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

public class Main {
   public static void main(String[] args) {
      
      Map<String, String> map = new HashMap<>();
      map.put("1", "A");
      map.put("2", "B");
      map.put("3", "C");
      
      Map<String, String> readOnlyMap = Collections.unmodifiableMap(map);
      System.out.println("Read-Only Map: " + readOnlyMap);
   
      try {
          readOnlyMap.put("4", "D");
      } catch (UnsupportedOperationException e) {
          System.out.println("Cannot modify read-only map: " + e);
      }
   }
}

Output

The above program produce the following result ?

Read-Only Map: {1=A, 2=B, 3=C}
Cannot modify read-only map: java.lang.UnsupportedOperationException
Updated on: 2024-12-31T22:00:07+05:30

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements