Java Utility Library

Java Collections - synchronizedSortedMap() Method



The java.util.Collections.synchronizedSortedMap() method returns a synchronized (thread-safe) sorted map backed by the specified sorted map.

Syntax

public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m)

Here, K and V are the type of key and value respectively maintained by the sorted map.


Parameters

m Specify the sorted map to be "wrapped" in a synchronized sorted map.

Return Value

Returns a synchronized view of the specified sorted map.

Exception

NA.

Example:

In the example below, the java.util.Collections.synchronizedSortedMap() method returns a synchronized view of the given sorted map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a SortedMap object
    SortedMap<Integer, String> MyMap = new TreeMap<Integer, String>();

    //populating MyMap
    MyMap.put(102, "John");
    MyMap.put(101, "Marry");
    MyMap.put(103, "Kim");

    //printing the map
    System.out.println("MyMap contains: " + MyMap); 

    //creating an synchronized view of the sorted map
    SortedMap NewMap = Collections.synchronizedSortedMap(MyMap);

    //printing the synchronized sorted map
    System.out.println("NewMap contains: " + NewMap); 
  }
}

The output of the above code will be:

MyMap contains: {101=Marry, 102=John, 103=Kim}
NewMap contains: {101=Marry, 102=John, 103=Kim}

❮ Java.util - Collections