This post will discuss various methods to create an unmodifiable map in Java.

Unmodifiable maps are “read-only” wrappers over other collections. They do not support any modification operations such as add, remove, and clear, but their underlying collection can be changed. Maps that additionally guarantee that no change in the Collection object will ever be visible are referred to as immutable.

Please note that making a map final will not make it Unmodifiable. We can still add elements or remove elements from it. Only the reference to the map is final.

1. Using Collections.unmodifiableMap() method

Collections unmodifiableMap() method returns an unmodifiable “read-only” view of the specified map. It takes another map and wraps it in a class that rejects modification requests, thus creating an unmodifiable view of the original map. Any attempt to modify the returned map directly or via its iterator will result in an UnsupportedOperationException.

However, it won’t create an inherently unmodifiable map. Having possession of a reference to the underlying collection still allows modification, i.e., any changes made to the original map will be reflected in the unmodifiable map. Also, each wrapper is an additional object, requiring another level of indirection and consuming more memory than the original collection. Finally, the wrapped collection still bears the expense of supporting mutation even if it is never intended to be modified.

Download  Run Code

Output:

java.lang.UnsupportedOperationException
{India=New Delhi}

2. Using Apache Commons Collections

Apache Commons Collections MapUtils class provides an unmodifiableMap() method that returns an unmodifiable map backed by the given map. If the given map is null, it throws a NullPointerException. The map will throw an UnsupportedOperationException if any modification operation is performed on it. However, any changes made to the original map will be reflected in the returned map.

Download Code

Output:

java.lang.UnsupportedOperationException
{India=New Delhi}

That’s all about unmodifiable Maps in Java.

 
Suggested Read:

Immutable Map in Java (using Guava and Java 9)

 
Reference: JEP 269: Convenience Factory Methods for Collections