Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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]
Advertisements