Java Utility Library

Java Collections - synchronizedSortedSet() Method



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

Syntax

public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s)

Here, T is the type of element in the sorted set.


Parameters

s Specify the sorted set to be "wrapped" in a synchronized sorted set.

Return Value

Returns a synchronized view of the specified sorted set.

Exception

NA.

Example:

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

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a SortedSet object
    SortedSet<Integer> MySet = new TreeSet<Integer>();

    //populating the set
    MySet.add(30);
    MySet.add(20);
    MySet.add(10);
    MySet.add(40);

    //printing the set
    System.out.println("MySet contains: " + MySet); 

    //creating an synchronized view of the sorted set
    SortedSet NewSet = Collections.synchronizedSortedSet(MySet);

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

The output of the above code will be:

MySet contains: [10, 20, 30, 40]
NewSet contains: [10, 20, 30, 40]

❮ Java.util - Collections