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.


What is Java LinkedHashSet?

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.

Key Features of LinkedHashSet:

  • Maintains Insertion Order: Unlike HashSet, which does not guarantee any order, LinkedHashSet preserves the order in which elements were added.
  • No Duplicates: Like other Set implementations, LinkedHashSet ensures that no duplicate elements can be added.
  • Efficient Performance: While slightly slower than 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().

Core Methods in LinkedHashSet

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:

1. add(E e)

Adds the specified element to the set. If the element already exists, it will not be added.

boolean add(E e);

2. remove(Object o)

Removes the specified element from the set.

boolean remove(Object o);

3. contains(Object o)

Checks if the set contains the specified element.

boolean contains(Object o);

4. size()

Returns the number of elements in the set.

int size();

5. isEmpty()

Checks if the set is empty.

boolean isEmpty();

6. clear()

Removes all elements from the set.

void clear();

7. forEach(Consumer<? super E> action)

Performs the given action for each element in the set.

void forEach(Consumer<? super E> action);

8. iterator()

Returns an iterator over the elements in the set in insertion order.

Iterator<E> iterator();

Creating and Using LinkedHashSet in Java

LinkedHashSet can be easily created using its constructor. Here’s how you can create and use it:

1. Creating an Empty LinkedHashSet

Set<String> linkedHashSet = new LinkedHashSet<>();

2. Creating a LinkedHashSet with Elements

You can also create a LinkedHashSet and populate it with elements right away:

Set<String> linkedHashSet = new LinkedHashSet<>(Arrays.asList("Apple", "Banana", "Orange"));

3. Creating a LinkedHashSet with Specific Initial Capacity and Load Factor

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);

Example: Using LinkedHashSet in Java

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: []

Explanation:

  • 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.
  • The 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.

Advantages of Using LinkedHashSet

  1. 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.

  2. No Duplicates: As a Set implementation, LinkedHashSet ensures that no duplicate elements are allowed, making it ideal for storing unique elements.

  3. 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.

  4. 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.


When to Use LinkedHashSet

You should consider using LinkedHashSet when:

  1. You Need to Preserve Insertion Order: When maintaining the order of elements is important, such as when you need to process elements in the same order in which they were added.
  2. You Want to Avoid Duplicates: If you need a collection that automatically prevents duplicates.
  3. Efficient Lookup and Insertion: When you require constant-time complexity for adding, removing, and checking for elements, along with predictable iteration order.

LinkedHashSet vs HashSet

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.