Skip to content
Related Articles

Related Articles

Getting Synchronized Set from Java HashSet
  • Last Updated : 07 Jan, 2021

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 HashSet as a parameter. To guarantee serial access, it is critical that all access to the backing set is accomplished through the returned set. The task is to get the synchronized set from a given HashSet.

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: HashSet as a parameter to be “wrapped” in a synchronized set.

Return Value: Synchronized view of the specified set.



Approach:

  1. Create a HashSet.
  2. Add some elements in the HashSet.
  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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to get synchronized
// set from hash set
import java.util.*;
public class GFG {
    public static void main(String args[])
    {
        // creating hash set
        Set<Integer> hash_set = new HashSet<Integer>();
        
        // adding the elements to hash set
        hash_set.add(1);
        hash_set.add(2);
        hash_set.add(3);
        hash_set.add(4);
        hash_set.add(5);
        
        // changing hash set to synchronized
        // set and storing in set
        Set synset = Collections.synchronizedSet(hash_set);
        System.out.println("Synchronized Set: " + synset);
    }
}

chevron_right


Output

Synchronized Set: [1, 2, 3, 4, 5]

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :