Java LinkedHashSet
The LinkedHashSet
is a class in the Java Collection Framework that implements the Set
interface and extends the HashSet
class. It maintains a linked list of the entries in the set, preserving the insertion order of elements. This means that elements will be returned in the order they were inserted.
It combines hash table performance with linked list ordering, making it a great choice when you need both uniqueness and ordering.
Characteristics of LinkedHashSet#
- Maintains insertion order of elements.
- No duplicate elements allowed.
- Allows one null element.
- Non-synchronized.
- Backed by a hash table with a linked list running through it.
Constructors of LinkedHashSet#
Constructor | Description |
---|---|
LinkedHashSet() | Creates a new, empty set with default capacity and load factor. |
LinkedHashSet(int initialCapacity) | Creates a new, empty set with specified initial capacity. |
LinkedHashSet(int initialCapacity, float loadFactor) | Creates a new, empty set with specified initial capacity and load factor. |
LinkedHashSet(Collection<? extends E> c) | Creates a set containing the elements of the specified collection. |
Example:#
Commonly Used Methods#
LinkedHashSet
inherits all methods from the Set
and Collection
interfaces:
Method | Description |
---|---|
add(E e) | Adds the specified element if not already present. |
remove(Object o) | Removes the specified element if present. |
contains(Object o) | Returns true if the set contains the element. |
size() | Returns the number of elements in the set. |
isEmpty() | Returns true if the set is empty. |
clear() | Removes all elements from the set. |
iterator() | Returns an iterator over the elements in insertion order. |
Example:#
Output:#
Performance Analysis#
Operation | Time Complexity |
---|---|
add(E e) | O(1) on average |
remove(Object o) | O(1) on average |
contains(Object o) | O(1) on average |
iteration | O(n) |
- Faster than TreeSet, but slightly slower than HashSet due to maintaining order.
- Ideal when both fast access and insertion order are needed.
Use Cases#
- When you need to maintain insertion order.
- Removing duplicates from a list while keeping original order.
- Caching or history tracking systems.
Example: Removing Duplicates from List While Maintaining Order#
Output:#
Conclusion#
In this blog, we explored the LinkedHashSet
class in Java. It offers the best of both worlds: the uniqueness property of a Set
and the ordering of a List
. We covered its characteristics, constructors, key methods, performance aspects, and use cases with examples. It's an excellent choice when you need a unique set with predictable iteration order.