If you need unique elements and preserve their insertion order...
๐งฉ LinkedHashSet
✅ Why LinkedHashSet?
- Uniqueness: Like all
Setimplementations, it does not allow duplicate elements. - Order preservation: It maintains the insertion order of elements, unlike
HashSetwhich does not guarantee any order.
๐ Comparison with Other Sets
| Set Type | Allows Duplicates | Maintains Order | Performance |
|---|---|---|---|
HashSet |
❌ | ❌ | Fastest |
LinkedHashSet |
❌ | ✅ | Slightly slower than HashSet |
TreeSet |
❌ | ✅ (Sorted order) | Slower due to sorting |
๐งช Example in Java
Set<String> orderedUniqueSet = new LinkedHashSet<>();
orderedUniqueSet.add("apple");
orderedUniqueSet.add("banana");
orderedUniqueSet.add("apple"); // Duplicate, won't be added
orderedUniqueSet.add("cherry");
System.out.println(orderedUniqueSet); // Output: [apple, banana, cherry]
This is especially useful in microservices where you need deterministic behavior in logs, configs, or event payloads. Want to explore how these fits into a Spring Boot use case or a real-world architecture pattern?
No comments:
Post a Comment