Create Immutable HashMap in Java

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.

🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.

▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube

In this tutorial, we will learn how to make immutable HashMap with an example.
Learn and master Java Collections Framework at Learn Java Collections Framework
We will see two examples to make immutable HashMap:
  • First, we will see how to create an immutable HashMap using Collections.unmodifiableMap() method with an example.
  • Second, we will see how to create an immutable HashMap using Java 9 provided Map.ofEntries() static factory method.

1. Create Immutable HashMap with Collections.unmodifiableMap() Method 

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}

2. Create immutable HashMap with Java 9 Map.ofEntries() factory method 

The below example shows how to create an immutable HashMap using Java 9 provided Map.ofEntries() static factory method.
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}

Conclusion

In this tutorial, we have seen how to make immutable HashMap using Collections.unmodifiableMap() method and Java 9 provided Map.ofEntries() static factory method with an example.

Collections Examples

References

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare