LinkedHashSet in Java
1. What is LinkedHashSet?
LinkedHashSet is a part of the Java Collection Framework (java.util package).
It extends HashSet and implements the Set interface.
Maintains insertion order, unlike HashSet.
Does not allow duplicate elements.
Uses hash table + linked list to store elements.
2. Key Features of LinkedHashSet
Maintains Insertion Order – Unlike HashSet, elements are stored in the order they
were inserted.
No Duplicates – Only unique elements are allowed.
Allows Null Values – Can store a single null value.
Not Thread-Safe – Needs synchronization for multi-threaded access
(Collections.synchronizedSet()).
Faster than TreeSet – Uses hashing for quick lookups but maintains order via a
linked list.
3. Example Program: Using LinkedHashSet in Java
import java.util.LinkedHashSet;
public class LinkedHashSetExample {
public static void main(String[] args) {
// Creating a LinkedHashSet
LinkedHashSet<String> cities = new LinkedHashSet<>();
// Adding elements
cities.add("New York");
cities.add("London");
cities.add("Paris");
cities.add("Tokyo");
cities.add("London"); // Duplicate, won't be added
// Displaying elements (insertion order maintained)
System.out.println("LinkedHashSet elements: " + cities);
// Checking if an element exists
System.out.println("Contains 'Paris'? " + cities.contains("Paris"));
// Removing an element
cities.remove("Tokyo");
System.out.println("After removing 'Tokyo': " + cities);
// Iterating using for-each loop
System.out.println("Iterating over LinkedHashSet:");
for (String city : cities) {
System.out.println(city);
}
// Checking size
System.out.println("Size of LinkedHashSet: " + cities.size());
// Clearing the LinkedHashSet
cities.clear();
System.out.println("Is LinkedHashSet empty? " + cities.isEmpty());
}
}
4. Output
LinkedHashSet elements: [New York, London, Paris, Tokyo]
Contains 'Paris'? true
After removing 'Tokyo': [New York, London, Paris]
Iterating over LinkedHashSet:
New York
London
Paris
Size of LinkedHashSet: 3
Is LinkedHashSet empty? true
5. Important Methods in LinkedHashSet
Method Description
add(E e) Adds an element to the LinkedHashSet.
remove(Object o) Removes the specified element.
contains(Object o) Checks if an element exists.
size() Returns the number of elements.
isEmpty() Checks if the LinkedHashSet is empty.
clear() Removes all elements.
iterator() Returns an iterator to traverse elements.
6. When to Use LinkedHashSet?
When unique elements are required (like HashSet).
When insertion order must be maintained (unlike HashSet).
When fast operations are needed (faster than TreeSet).