Get Synchronized Set from HashSet in Java


The synchronizedSet() method returns a synchronized (thread-safe) sorted set backed by the specified sorted set.

First, create a HashSet and add elements −

Set<Integer> hs = new HashSet<Integer>();
hs.add(29);
hs.add(879);
hs.add(88);
hs.add(788);
hs.add(456);

Now, to get synchronized set, use the synchronizedSet() method −

Set s = Collections.synchronizedSet(hs);

The following is an example to get synchronized set from HashSet −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      Set<Integer> hs = new HashSet<Integer>();
      hs.add(29);
      hs.add(879);
      hs.add(88);
      hs.add(788);
      hs.add(456);
      Set s = Collections.synchronizedSet(hs);
      System.out.println("Synchronized Set = "+s);
   }
}

Output

Synchronized Set = [788, 88, 456, 29, 879]

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

239 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements