CodesJava

Easy learning with example program codes

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.codesjava;
 
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.codesjava.Test.main(Test.java:27)

Java Collections class examples

Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki