Converting a map to immutable map

In this post under Java Collections, I will show with example how to obtain an immutable map.

Below is the complete main code for your reference

Main class

1  package core.collection;
2  
3  import java.util.Collections;
4  import java.util.HashMap;
5  import java.util.Map;
6  
7  public class ImmutableMapDemo {
8      public static void main(String[] args) {
9          Map<Integer, String> map = new HashMap<>(0);
10         map.put(1, "Id");
11         map.put(2, "Name");
12         map.put(3, "Salary");
13 
14         Map<Integer, String> immutableMap = Collections.unmodifiableMap(map);
15 
16         System.out.println(immutableMap);
17     }
18 }

In the above code, at line 9, I create a map with key type “Integer” and value type as “String” and then I populate it.

At line 14, I create an immutable map by calling static method “unmodifiableMap” available on “Collections” class and passing the map as an argument.

In this way, we can create a immutable map.

Please note once we obtain an immutable map, any modification to source map will affect the immutable map.

Leave a comment