Collections Framework · Lesson 79 of 150
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.
01What 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.
02Why 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.
03Real-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.
04Syntax
javaLinkedHashSet<DataType> setName = new LinkedHashSet<>();
05Example Program
javaimport 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]06Key Points to Remember
LinkedHashSetkeeps elements in the order they were inserted, unlikeHashSet.- It's slightly slower than
HashSetdue to the extra work of maintaining order. - Choose
LinkedHashSetwhen both uniqueness and predictable order are needed.