The synchronizedSortedMap() method of java.util.Collections class is used to return a synchronized (thread-safe) sorted map backed by the specified sorted map. In order to guarantee serial access, it is critical that all access to the backing sorted map is accomplished through the returned sorted map (or its views).
Syntax:
public static <K, V> SortedMapK, V>
synchronizedSortedMap(SortedMapK, V> m)
Parameters: This method takes the sorted map as a parameter to be “wrapped” in a synchronized sorted map.
Return Value: This method returns a synchronized view of the specified sorted map.
Below are the examples to illustrate the synchronizedSortedMap() method
Example 1:
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( "1" , "A" );
map.put( "2" , "B" );
map.put( "3" , "C" );
System.out.println( "Sorted Map : " + map);
SortedMap<String, String>
sortedmap = Collections
.synchronizedSortedMap(map);
System.out.println( "Synchronized sorted map is :"
+ sortedmap);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Sorted Map : {1=A, 2=B, 3=C}
Synchronized sorted map is :{1=A, 2=B, 3=C}
Example 2:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
SortedMap<Integer, Boolean>
map = new TreeMap<Integer, Boolean>();
map.put( 100 , true );
map.put( 200 , true );
map.put( 300 , true );
System.out.println( "Sorted Map : " + map);
SortedMap<Integer, Boolean>
sortedmap = Collections
.synchronizedSortedMap(map);
System.out.println( "Synchronized sorted map is :"
+ sortedmap);
}
catch (IllegalArgumentException e) {
System.out.println( "Exception thrown : " + e);
}
}
}
|
Output:
Sorted Map : {100=true, 200=true, 300=true}
Synchronized sorted map is :{100=true, 200=true, 300=true}
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
08 Oct, 2018
Like Article
Save Article