Create an Immutable HashMap Example

In this post, we will learn how to create an immutable HashMap before Java 9 and using Java 9 provided Map.ofEntries() static factory method.

Create an Immutable HashMap Example

Refer the comments are self-descriptive.

package com.java.tutorials.java9;

import java.util.Collections;
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");

        // before java 9
        fruits = Collections.unmodifiableMap(fruits);
        System.out.println(fruits);

        // 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}
{1=Banana, 2=Mango, 3=Apple}

References

Related HashMap Source Code Examples


Comments