Get Synchronized Set from HashSet in Java

Java 8Object Oriented ProgrammingProgramming

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]
raja
Published on 16-Jan-2019 07:26:36
Advertisements