To store elements in a Set while maintaining the order in which they were added, Java provides the LinkedHashSet class. LinkedHashSet combines the uniqueness property of a Set with a linked list structure that preserves insertion order during iteration.
Key Points: • LinkedHashSet maintains elements in the order they are inserted. • Duplicate elements are not allowed. • Internally uses a hash table and a linked list. • Provides predictable iteration order. • Performance is similar to HashSet for most operations.
Why Not HashSet?
HashSet does not guarantee any iteration order.
Example:
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Spring");
set.add("Hibernate");The output order may vary and should not be relied upon.
Why Use LinkedHashSet?
LinkedHashSet remembers the insertion sequence and returns elements in the same order.
Example:
Java → Spring → Hibernate
The iteration order remains the same.
Example: Suppose we want to store unique technologies while preserving the order in which they were added.
Code Example:
import java.util.LinkedHashSet;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
Set<String> technologies =
new LinkedHashSet<>();
technologies.add("Java");
technologies.add("Spring");
technologies.add("Hibernate");
technologies.add("Java");
System.out.println(technologies);
}
}Output:
[Java, Spring, Hibernate]
Notice:
• The duplicate "Java" is ignored. • The insertion order is preserved.
Comparison of Common Set Implementations:
HashSet: • Maintains uniqueness • Does not preserve insertion order • Fastest for general-purpose usage
LinkedHashSet: • Maintains uniqueness • Preserves insertion order • Slightly more memory usage than HashSet
TreeSet: • Maintains uniqueness • Stores elements in sorted order • Does not preserve insertion order
Real-World Use Cases:
• Maintaining a unique list of recently viewed products • Preserving user-selected options • Generating reports where insertion order matters • Removing duplicates while keeping the original sequence
Interview Tip: A concise interview answer is:
"Use LinkedHashSet when you need a Set that prevents duplicate elements while preserving the order in which elements were inserted. It achieves this by maintaining a linked list alongside the hash table, ensuring predictable iteration order."