how to create immutable map in java?

The java.util.Collections class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.

Collections.unmodifiableMap() method is used to create immutable set in java. It will throws an exception if we try to add, remove or shift elements.

Example

package com.w3spoint;
 
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
 
public class Test {
	public static void main(String args[]){
		//Create HashMap object.
		Map<Integer, String> hashMap = new HashMap<Integer, String>();
 
		//Add objects to the HashSet.
		hashMap.put(4, "Roxy");
		hashMap.put(2, "Sunil");
		hashMap.put(5, "Sandy");
		hashMap.put(1, "Munish");
		hashMap.put(3, "Pardeep");
 
		//Print the HashMap object.
		System.out.println("HashMap elements:");
		System.out.println(hashMap);
 
		//Immutable map
		Map<Integer, String> immutableMap = Collections.unmodifiableMap(hashMap);
 
		//Add element
		immutableMap.put(6, "Naren");
	}
}

Output

HashMap elements:
{1=Munish, 2=Sunil, 3=Pardeep, 4=Roxy, 5=Sandy}
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.Collections$UnmodifiableMap.put(Unknown Source)
	at com.w3spoint.Test.main(Test.java:27)

Java Collections class examples

Please follow and like us:
Content Protection by DMCA.com