LinkedHashSet

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, a LinkedHashSet remembers the order in which elements were added.
  • No Duplicates: Just like a HashSet, a LinkedHashSet 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 a HashSet.

Example

In the above example:

  • Even though we tried to add "Apple" twice, the LinkedHashSet 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.