In Java, a Set is part of the Java Collections Framework and is used to store unique elements .
The main rule of Set:
No duplicate values allowed
What is a Set?
A Set is a collection that:
Does not allow duplicates
Does not maintain index
Can store null values (depends on implementation)
Types of Set in Java
1. HashSet
Does not maintain order
Fast performance
Allows one null value
HashSet < String > set = new HashSet <>(); set . add ( "Apple" ); set . add ( "Banana" ); set . add ( "Apple" ); // duplicate ignored
System . out . println ( set );
Enter fullscreen mode
Exit fullscreen mode
2. LinkedHashSet
Maintains insertion order
Slightly slower than HashSet
LinkedHashSet < String > set = new LinkedHashSet <>(); set . add ( "Apple" ); set . add ( "Banana" ); set . add ( "Mango" );
System . out . println ( set );
Enter fullscreen mode
Exit fullscreen mode
3. TreeSet
Stores elements in sorted order
Uses natural sorting
Does not allow null
TreeSet set = new TreeSet<>();
set .…