Java LinkedHashSet
In Java, the LinkedHashSet
class is a powerful implementation of the Set
interface that combines the characteristics of both a HashSet
and a LinkedList
. It ensures that elements are stored in a unique collection while maintaining their insertion order. This makes LinkedHashSet
an ideal choice when you need to maintain the order in which elements were added to the set, while still benefiting from the fast performance of HashSet
operations.
The LinkedHashSet
class is part of the java.util
package and implements the Set
interface. It is similar to HashSet
but with an additional feature: it maintains the insertion order of elements. Internally, LinkedHashSet
uses a hash table (like HashSet
) to store elements and a doubly linked list to maintain the order of insertion.
HashSet
, which does not guarantee any order, LinkedHashSet
preserves the order in which elements were added.Set
implementations, LinkedHashSet
ensures that no duplicate elements can be added.HashSet
due to the overhead of maintaining insertion order, LinkedHashSet
still provides efficient constant time performance for basic operations such as add()
, remove()
, and contains()
.The LinkedHashSet
class implements methods from the Set
interface, similar to HashSet
, but with additional features to maintain the insertion order. Here are some commonly used methods:
Adds the specified element to the set. If the element already exists, it will not be added.
boolean add(E e);
Removes the specified element from the set.
boolean remove(Object o);
Checks if the set contains the specified element.
boolean contains(Object o);
Returns the number of elements in the set.
int size();
Checks if the set is empty.
boolean isEmpty();
Removes all elements from the set.
void clear();
Performs the given action for each element in the set.
void forEach(Consumer<? super E> action);
Returns an iterator over the elements in the set in insertion order.
Iterator<E> iterator();
LinkedHashSet
can be easily created using its constructor. Here’s how you can create and use it:
Set<String> linkedHashSet = new LinkedHashSet<>();
You can also create a LinkedHashSet
and populate it with elements right away:
Set<String> linkedHashSet = new LinkedHashSet<>(Arrays.asList("Apple", "Banana", "Orange"));
You can specify the initial capacity and the load factor to fine-tune the set’s performance:
Set<String> linkedHashSet = new LinkedHashSet<>(16, 0.75f);
Here’s an example demonstrating how to use LinkedHashSet
to store and manage elements while maintaining insertion order:
import java.util.*;
public class LinkedHashSetExample {
public static void main(String[] args) {
// Create a LinkedHashSet to store unique fruits
Set<String> fruits = new LinkedHashSet<>();
// Add elements to the set
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Apple"); // Duplicate element, won't be added
fruits.add("Grape");
// Print all elements (order of insertion is preserved)
System.out.println("Fruits in LinkedHashSet: " + fruits);
// Check if a specific element exists
System.out.println("Contains 'Banana': " + fruits.contains("Banana")); // true
// Remove an element
fruits.remove("Orange");
System.out.println("After removing Orange: " + fruits);
// Get the size of the set
System.out.println("Size of the set: " + fruits.size()); // 3
// Check if the set is empty
System.out.println("Is the set empty? " + fruits.isEmpty()); // false
// Iterate through the set in insertion order
System.out.println("Iterating over LinkedHashSet:");
for (String fruit : fruits) {
System.out.println(fruit);
}
// Clear the set
fruits.clear();
System.out.println("Fruits after clearing: " + fruits); // Output: []
}
}
Output:
Fruits in LinkedHashSet: [Apple, Banana, Orange, Grape]
Contains 'Banana': true
After removing Orange: [Apple, Banana, Grape]
Size of the set: 3
Is the set empty? false
Iterating over LinkedHashSet:
Apple
Banana
Grape
Fruits after clearing: []
add()
ensures that Apple
is only added once, even though it was attempted twice.contains()
checks if the set contains Banana
.remove()
removes Orange
from the set.size()
returns the number of elements in the set.isEmpty()
checks if the set is empty.for-each loop
iterates over the set, and the elements are printed in the order in which they were added.clear()
removes all elements from the set.Maintains Insertion Order: Unlike HashSet
, LinkedHashSet
guarantees that the elements are returned in the order in which they were inserted. This is useful when you need to process the elements in the same order as they were added.
No Duplicates: As a Set
implementation, LinkedHashSet
ensures that no duplicate elements are allowed, making it ideal for storing unique elements.
Efficient Performance: LinkedHashSet
provides constant time performance O(1) for add()
, remove()
, and contains()
operations, similar to HashSet
, but with a slightly more overhead due to maintaining the insertion order.
Iteration Order: It provides predictable iteration order, which is useful when the order of elements matters but you still need the properties of a set.
You should consider using LinkedHashSet
when:
Feature | LinkedHashSet |
HashSet |
---|---|---|
Order of Elements | Maintains insertion order. | No specific order. |
Performance | Slightly slower than HashSet due to linked list overhead. |
Faster for basic operations, as no order is maintained. |
Use Case | When insertion order matters. | When order does not matter. |