Collections unmodifiableSortedMap() method in Java with Examples
Last Updated :
02 May, 2023
The unmodifiableSortedMap() method of java.util.Collections class is used to return an unmodifiable view of the specified sorted map. This method allows modules to provide users with “read-only” access to internal sorted maps. Query operations on the returned sorted map “read through” to the specified sorted map. Attempts to modify the returned sorted map, whether direct, via its collection views, or via its subMap, headMap, or tailMap views, result in an UnsupportedOperationException. The returned sorted map will be serializable if the specified sorted map is serializable.
Syntax:
public static <K, V> SortedMap<K, V>
unmodifiableSortedMap(SortedMap<K, ? extends V> m)
Parameters: This method takes the sorted map as a parameter for which an unmodifiable view is to be returned.
Return Value: This method returns an unmodifiable view of the specified sorted map.
Below are the examples to illustrate the unmodifiableSortedMap() method
Example 1:
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
SortedMap<String, String>
map = new TreeMap<String, String>();
map.put("First", " 10 ");
map.put("Second", " 20 ");
map.put("Third", " 30 ");
Map<String, String>
unmodsortmap = Collections
.unmodifiableSortedMap(map);
System.out.println("Initial sorted map value: "
+ map);
}
catch (UnsupportedOperationException e) {
System.out.println("Exception thrown : " + e);
}
}
}
|
Output:
Initial sorted map value: {First=10, Second=20, Third=30}
Example 2: For UnsupportedOperationException
Java
import java.util.*;
public class GFG1 {
public static void main(String[] argv) throws Exception
{
try {
SortedMap<String, String>
map = new TreeMap<String, String>();
map.put("First", " 10 ");
map.put("Second", " 20 ");
map.put("Third", " 30 ");
Map<String, String>
unmodsortmap = Collections
.unmodifiableSortedMap(map);
System.out.println("unmodifiableSortedMap value: "
+ map);
System.out.println("\nTrying to modify"
+ " the unmodifiable SortedMap");
unmodsortmap.put("Fourth", " 40 ");
}
catch (UnsupportedOperationException e) {
System.out.println("Exception thrown : " + e);
}
}
}
|
Output:
unmodifiableSortedMap value: {First=10, Second=20, Third=30}
Trying to modify the unmodifiable SortedMap
Exception thrown : java.lang.UnsupportedOperationException
Share your thoughts in the comments
Please Login to comment...