Java – How to make a HashMap read-only or unmodifiable ?

In this article, we will discuss how to convert a modifiable HashMap entries into an unmodifiable HashMap entries using Collections.unmodifiableMap(); method

1. Convert HashMap to Read-only:

  • HashMap is an implementation-class of Map interface which grows/shrink in size dynamically whenever entries is
    • added to a HashMap using put() method
    • deleted from existing HashMap using remove() method
    • updated/modified from existing HashMap using replace() method
  • For some business purpose/requirement, HashMap needs to be made read-only or immutable or unmodifiable
  • To achieve this, use one of the utility method called unmodifiableMap() from Collections class
  • Syntax : Collections.unmodifiableMap(modifiableMap); i.e.; pass modifiable map as input-argument
  • Trying to add/remove/modify an unmodifiable Map throws UnsupportedOperationException as shown in the below example
  • Note: however, adding/deleting/updating Map entries in the original HashMap is still possible

ConvertHashMapToReadOnly.java

package net.bench.resources.unmodifiable.collection;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class ConvertHashMapToReadOnly {

	public static void main(String[] args) {

		// 1. HashMap
		Map<String, String> map = new HashMap<>();


		// 1.1 add Map entries
		map.put("America", "Biden");
		map.put("Russia", "Putin");
		map.put("India", "Modi");
		map.put("China", "Xi");


		// 1.2 iterating/printing original List
		System.out.println("1. Orginal Map entries : \n");
		map.forEach((key, value) -> System.out.println(key + "\t" + value));


		// 2. convert modifiable map to immutable map
		Map<String, String> unmodifiableMap = Collections
				.unmodifiableMap(map);


		// 2.1 iterating/printing original Map
		System.out.println("\n\n2. Read-only Map : \n");
		unmodifiableMap.forEach((key, value) -> System.out.println(key + "\t" + value));


		// 3. trying to modify unmodifiable map
		System.out.println("\n\n3. Trying to modify unmodifiable map : \n");
		try {
			unmodifiableMap.put("British", "Boris");
		}
		catch(UnsupportedOperationException usopex) {
			System.out.println("In Exception block : ");
			usopex.printStackTrace();
		}
	}
}

Output:

1. Orginal Map entries : 

China	Xi
America	Biden
Russia	Putin
India	Modi


2. Read-only Map : 

China	Xi
America	Biden
Russia	Putin
India	Modi


3. Trying to modify unmodifiable map : 

In Exception block : 
java.lang.UnsupportedOperationException
	at java.util.Collections$UnmodifiableMap.put(Collections.java:1457)
	at net.bench.resources.unmodifiable.collection.ConvertHashMapToReadOnly
.main(ConvertHashMapToReadOnly.java:40)

Related Articles:

References :

Happy Coding !!
Happy Learning !!

Java 8 - How to remove duplicate from Arrays ?
Java - How to make a HashSet read-only or unmodifiable ?