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);
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);
3. TreeSet
- Stores elements in sorted order
- Uses natural sorting
- Does not allow null
TreeSet set = new TreeSet<>();
set.add(30);
set.add(10);
set.add(20);
System.out.println(set); // [10, 20, 30]
Key Features of Set
- No duplicates
- Unordered (except LinkedHashSet & TreeSet)
- No index-based access
- Faster search operations
When to Use Set?
Use Set when:
- You want to remove duplicates
- You only care about unique values
- Order is not important (use HashSet)
List vs Set (Quick Idea)
| Feature | List | Set |
|---|---|---|
| Duplicates | Allowed | Not allowed |
| Order | Maintained | Not guaranteed |
| Index access | Yes | No |
Real-Life Example
Set → Like a collection of unique IDs
(No two IDs can be the same)
Final Thoughts
If your data should be unique, always go for Set instead of List.
Top comments (0)