Create Immutable HashMap with Collections.unmodifiableMap() Example

In this example, we will see how to create an immutable HashMap using Collections.unmodifiableMap() method with an example.

Create Immutable Map

Prior to Java 9, we create an immutable HashMap using Collections.unmodifiableMap() method like:
public class ImmutableMapExample {

    public static void main(String[] args) {

        // Creating a HashMap
        Map < String, Integer > numberMapping = new HashMap < > ();

        // Adding key-value pairs to a HashMap
        numberMapping.put("One", 1);
        numberMapping.put("Two", 2);
        numberMapping.put("Three", 3);

        Collections.unmodifiableMap(numberMapping);
        System.out.println(fruits);
    }
}
Output:
{One=1, Two=2, Three=3}
Using Java 9 is quite easy:
import java.util.HashMap;
import java.util.Map;


public class ImmutableHashMap {

    public static void main(String[] args) {

        Map < String, String > fruits = new HashMap < String, String > ();
        fruits.put("1", "Banana");
        fruits.put("2", "Mango");
        fruits.put("3", "Apple");

        // java 9 with factory methods
        Map < String, String > map = Map.ofEntries(
            Map.entry("1", "Banana"),
            Map.entry("2", "Mango"),
            Map.entry("3", "Apple"));

        System.out.println(map);
    }
}
Output:
{1=Banana, 2=Mango, 3=Apple}

Comments