Skip to content
C

LinkedHashSet

LinkedHashSet is a variation of HashSet that maintains the insertion order of elements — meaning elements appear in the same order they were added, while still preventing duplicates.


1. What is LinkedHashSet?

LinkedHashSet is a variation of HashSet that maintains the insertion order of elements — meaning elements appear in the same order they were added, while still preventing duplicates.

2. Why is it used?

It's useful when you need the uniqueness guarantee of a Set, but also want to preserve a predictable, consistent order of elements, unlike a regular HashSet.

3. Real-Life Example

Think of a guest list at an event where each guest's name is unique, and names are recorded in exactly the order they registered. LinkedHashSet preserves this registration order while ensuring no repeated names.

4. Syntax

java
LinkedHashSet<DataType> setName = new LinkedHashSet<>();

5. Example Program

java
import java.util.LinkedHashSet; public class LinkedHashSetDemo { public static void main(String[] args) { LinkedHashSet<String> visitors = new LinkedHashSet<>(); visitors.add("Karan"); visitors.add("Divya"); visitors.add("Karan"); // duplicate, ignored System.out.println(visitors); } }

Output:

[Karan, Divya]

6. Key Points to Remember

  • LinkedHashSet keeps elements in the order they were inserted, unlike HashSet.
  • It's slightly slower than HashSet due to the extra work of maintaining order.
  • Choose LinkedHashSet when both uniqueness and predictable order are needed.