102
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
Parameter | Description | Required/Optional |
---|---|---|
m | It 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
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=TutorAspire}
Example 2
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
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}
Next TopicJava Collections Class