HashSet that preserves ordering
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
When working with collections in programming, especially in languages like Java, developers often need a data structure that can store unique elements. The `HashSet` is a popular choice due to its constant time performance for basic operations like add, remove, and contains. However, traditional `HashSet` does not maintain any order of the elements. This article explores a variant of `HashSet` that preserves the order in which elements are added, often referred to as `LinkedHashSet`.
Overview of HashSet
`HashSet` is a part of the Java Collections Framework and implements the `Set` interface. It is backed by a `HashMap` instance, thus most of the operations have a constant time complexity. Elements are stored in a hash table and it does not guarantee any specific order in which the elements are stored or retrieved.
Key Characteristics of HashSet
- No Duplicate Elements: Ensures no duplicate entries.
- Order Not Maintained: The order of elements is not preserved.
- Constant Time Performance: Offers average time complexity for operations like add, remove, and contains.
- Allows `null` Values: Can store a single null value.
Preserving Order with LinkedHashSet
To maintain the insertion order of elements, Java provides `LinkedHashSet`. `LinkedHashSet` extends `HashSet` and maintains a doubly-linked list across all entries. This linked list defines the iteration ordering, which is the order in which the elements were inserted into the set.
Characteristics of LinkedHashSet
- Order Preservation: Maintains insertion order of elements.
- No Duplicate Elements: Similar to `HashSet`, no duplicate entries are allowed.
- Iteration: Iterates over elements in their insertion order.
- lower Performance Overhead: Due to the operation of maintaining order, there's a minimal performance overhead compared to `HashSet`.
Technical Details
- Performance: Slightly slower than `HashSet` but offers similar complexity for operations.
- Memory Usage: Uses more memory due to the overhead of the linked list maintaining insertion order.
Example Usage
Here's a simple example illustrating the usage of `LinkedHashSet`:
- Caching: `LinkedHashSet` can be used for caching order-sensitive data.
- Data Deduplication: Ideal where maintaining the first occurrence of elements is needed.
Related reading

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.