A LinkedHashSet
is part of Java’s Collection framework and is a variation of the regular HashSet
. It provides the same functionality as a HashSet
(i.e., it stores unique elements), but with one key difference: it maintains the insertion order of elements. This means that the order in which you add elements to the LinkedHashSet
is the order in which they will be iterated over.
Features
- Maintains Insertion Order: Unlike a
HashSet
, which does not guarantee any specific order of elements, aLinkedHashSet
remembers the order in which elements were added. - No Duplicates: Just like a
HashSet
, aLinkedHashSet
does not allow duplicate elements. - Efficient: It combines the performance benefits of a hash table with the ordering capability of a linked list. The elements are stored in a hash table, but the linked list ensures that they maintain their insertion order.
- Null Values: It allows the storage of
null
elements, just like aHashSet
.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.LinkedHashSet; public class LinkedHashSetExample { public static void main(String[] args) { // Creating a LinkedHashSet LinkedHashSet<String> fruits = new LinkedHashSet<>(); // Adding elements fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); fruits.add("Mango"); // Duplicates will not be added fruits.add("Apple"); // Printing the LinkedHashSet System.out.println(fruits); // Output: [Apple, Banana, Orange, Mango] } } |
In the above example:
- Even though we tried to add
"Apple"
twice, theLinkedHashSet
only stores one instance of it. - The elements are printed in the order they were added:
Apple, Banana, Orange, Mango
.
Use Cases
- Maintaining Order: Use
LinkedHashSet
when you need to store unique elements but also require them to be ordered according to their insertion sequence. - Removing Duplicates while Preserving Order: If you need to remove duplicates from a list while keeping the original order intact,
LinkedHashSet
is a perfect choice. - Cache Implementations:
LinkedHashSet
can be used in implementing caches where the order of access matters. - Efficient Membership Testing: When the uniqueness of elements is important and you need to frequently check for membership,
LinkedHashSet
provides an efficient solution.