Wednesday, October 15, 2025
HomeLanguagesJavaGetting Synchronized Set from Java TreeSet

Getting Synchronized Set from Java TreeSet

In java.util.Collections class, synchronizedSet() method is used to return a synchronized (thread-safe) set backed by the specified set. This method takes the TreeSet as a parameter. To guarantee serial access, it is critical that all access to the backing set is accomplished through the returned set. We have Java TreeSet, our task is to get a synchronized set from it. For this, use synchronizedSet method of the Collections class.

Example:

Input : HashSet = [3, 4, 5]
Output: synchronizedSet = [3, 4, 5]

Input : HashSet = ['A', 'B', 'C']
Output: synchronizedSet = ['A', 'B', 'C']

Syntax:

public static <T> Set<T> synchronizedSet(Set<T> s)

Parameters: TreeSet as a parameter to be “wrapped” in a synchronized set.

Return Value: 

Synchronized view of the specified set.

Approach:

  1. Create a TreeSet.
  2. Add some elements in the TreeSet.
  3. Create a Set variable and assign it with the Collections.synchronizedSet() method.
  4. Print the new synchronized Set.

Below is the implementation of the above approach:

Java




// Java program to get synchronized
// set from given tree set
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
  
class GFG {
    public static void main(String[] args)
    {
        TreeSet<Integer> treeSet = new TreeSet<Integer>();
  
        // Elements are added using add() method
        treeSet.add(48);
        treeSet.add(49);
        treeSet.add(59);
        treeSet.add(38);
        System.out.println("TreeSet : "+treeSet);
  
        // converting tree set to synchronized set
        Set set = Collections.synchronizedSet(treeSet);
        System.out.println("SynchronizedSet : "+set);
    }
}


Output

TreeSet : [38, 48, 49, 59]
SynchronizedSet : [38, 48, 49, 59]
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11891 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11952 POSTS0 COMMENTS
Shaida Kate Naidoo
6851 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS