LinkedHashSet in Java

Naveen AnamaneniUpdated · 4 min read

LinkedHashSet in Java is a class that extends HashSet and keeps its elements in insertion order. It is used when you need unique elements, like a HashSet, but also want to get them back in the order they were added. Inside, it uses a hash table for fast lookup plus a doubly linked list that runs through all the elements to remember their order. In this lesson, you will learn how to use LinkedHashSet and how it compares with the other sets.

Declaration

Declaration
public class LinkedHashSet<E> extends HashSet<E>
        implements SequencedSet<E>, Cloneable, Serializable

Since Java 21, LinkedHashSet also implements SequencedSet, which adds methods such as getFirst, getLast and reversed.

Features of LinkedHashSet

  • Unique elements, like every set.
  • Insertion order is kept. Adding an element that is already present does not move it.
  • Allows one null.
  • Fast: add, remove and contains are constant time on average, a little slower than HashSet because of the links.
  • Not synchronized.

Example: Order Is Kept

Let's see an example comparing HashSet and LinkedHashSet with the same input.

OrderDemo.java▶ Try it
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
 
public class OrderDemo {
    public static void main(String[] args) {
        List<String> visits = List.of("Pune", "Agra", "Delhi", "Agra",
                                      "Mumbai", "Pune", "Chennai");
 
        Set<String> linked = new LinkedHashSet<>(visits);
        System.out.println("LinkedHashSet: " + linked);
 
        Set<String> hash = new HashSet<>(visits);
        System.out.println("HashSet size:  " + hash.size());
    }
}
Output
LinkedHashSet: [Pune, Agra, Delhi, Mumbai, Chennai]
HashSet size:  5

Explanation: Both sets drop the repeated Agra and Pune and keep 5 cities. The LinkedHashSet lists them in the order they were first visited. A HashSet would list them in an order that depends on hash codes, which is why only its size is printed here.

Example: Sequenced Methods (Java 21)

SequencedDemo.java▶ Try it
import java.util.LinkedHashSet;
import java.util.List;
 
public class SequencedDemo {
    public static void main(String[] args) {
        LinkedHashSet<String> names = new LinkedHashSet<>(
            List.of("Navika", "Srihitha", "Advitha"));
        System.out.println("First: " + names.getFirst());
        System.out.println("Last: " + names.getLast());
        System.out.println("Reversed: " + names.reversed());
 
        names.addFirst("Anamaneni");
        System.out.println(names);
    }
}
Output
First: Navika
Last: Advitha
Reversed: [Advitha, Srihitha, Navika]
[Anamaneni, Navika, Srihitha, Advitha]

Explanation: getFirst and getLast read the ends of the order. reversed() returns a reversed view. addFirst puts an element at the front; if it were already in the set, it would be moved there.

HashSet vs LinkedHashSet vs TreeSet

HashSetLinkedHashSetTreeSet
OrderNoneInsertion orderSorted
add/containsO(1)O(1), slightly slowerO(log n)
nullOne allowedOne allowedNot allowed
MemoryLeastMore (links)More (tree nodes)
Use whenOrder doesn't matterOrder of arrival mattersSorted order or ranges matter

Common Mistakes

Expecting a re-added element to move to the end. add leaves it where it was; remove it first, or use addLast.

Using TreeSet when insertion order is what you need. TreeSet sorts; LinkedHashSet remembers arrival order.

Practice

  1. Easy: Remove duplicate characters from the word "Anamaneni" while keeping their first-seen order.
  2. Harder: Keep a "recently viewed" list of product IDs with no duplicates, where viewing a product again moves it to the end.

Quick check: LinkedHashSet

4 questions
1What order does LinkedHashSet keep?
2Which class does LinkedHashSet extend?
3What happens when you add an element that's already present?
4Which method does LinkedHashSet gain from SequencedSet?

Key Takeaways

Was this tutorial helpful?

Lesson 274 of 482