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.


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);

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


{1=Banana, 2=Mango, 3=Apple}
{1=Banana, 2=Mango, 3=Apple}


Related HashMap Source Code Examples

Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course