Kubernate

Java8 # Program # Requirement - Unique elements and preserve their insertion order

If you need unique elements and preserve their insertion order...

๐Ÿงฉ LinkedHashSet

✅ Why LinkedHashSet?

  • Uniqueness: Like all Set implementations, it does not allow duplicate elements.
  • Order preservation: It maintains the insertion order of elements, unlike HashSet which 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

Spring Boot - Bean LifeCycle

 Here is a clear, step-by-step lifecycle of a Spring Boot application , explained in a simple + interview-ready way. ๐Ÿ”„ Spring Boot Applica...

Kubernate