Java Collections unmodifiableMap() Method

The unmodifiableMap() method of Java Collections class is used to get an unmodifiable view of the specified map.

Syntax

Following is the declaration of unmodifiableMap() method:

Parameter

ParameterDescriptionRequired/Optional
mIt is the map for which an unmodifiable view is to be returned.Required

Returns

The unmodifiableMap() method returns an unmodifiable view of the specified map.

Exceptions

NA

Example 1

Test it Now

Output:

Initial collection: {key1=Java, key2=Android, key3=JavaScript}
Unmodifiable Map: {key1=Java, key2=Android, key3=JavaScript}
Unmodifiable Map after adding: {key1=Java, key2=Android, key3=JavaScript, key4=JavaTpoint}

Example 2

Test it Now

Output:

Initial Unmodifiable Map: {1=one, 2=two}
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.Collections$UnmodifiableMap.put(Collections.java:1453)
	at myPackage.CollectionsUnmodifiableMapExample2.main(CollectionsUnmodifiableMapExample2.java:10)

Example 3

Test it Now

Output:

Unmodifiable map: {1=1001, 2=1002, 3=1003, 4=1004, 5=1005}
Unmodifiable map after remove(4, 1004): {1=1001, 2=1002, 3=1003, 5=1005}





Latest Courses