Scrivio Interview library
ConceptFoundations5 min read · updated 12 November 2026

When would you use LinkedHashSet, what is its cost, and what did Java 21's SequencedSet add?

We use LinkedHashSet when we want a set that remembers insertion order, for example to remove duplicates from a list while keeping the original order, and it still gives O(1) add, remove and contains. Re-adding an element that is already present does not move it. The cost is extra memory for the before and after links on each entry, and like HashSet it is not thread-safe. Java 21 made it a SequencedSet, adding getFirst, getLast, removeFirst, removeLast, reversed, and addFirst and addLast, which move an existing element to that end.

Why this question is asked

Many everyday tasks need both uniqueness and a predictable order: the tags of an article as the author typed them, the list of recently viewed products, or the columns of a CSV without repeats. A HashSet gives uniqueness but an order that looks random and can change as the set grows, and a List gives order but no fast uniqueness check. Interviewers ask about LinkedHashSet to see whether we know the class that gives both, what it costs, and how Java 21 finally gave it convenient methods for its first and last elements. In this answer, we will recap how LinkedHashSet keeps its order, look at its typical uses and costs, and then go through the SequencedSet methods with code.

1A Quick Recap of How LinkedHashSet Keeps Order

LinkedHashSet extends HashSet, and underneath it uses a LinkedHashMap instead of a HashMap. A LinkedHashMap is a HashMap whose entries also form a doubly linked list: each entry has a before link to the previous entry and an after link to the next one, in the order they were inserted. Lookups still go through the hash table, so they are fast, while iteration follows the linked list from the oldest entry to the newest, so the order is predictable.

Because both structures are kept together, add, remove and contains remain O(1) on average, just like HashSet. Adding an element appends it to the end of the list; removing it unlinks it in constant time, because the entry knows its neighbours.

The same elements in two sets
Set typeIteration order after adding c, a, b
HashSetdepends on hash codes, for example [a, b, c]
LinkedHashSetinsertion order: [c, a, b]
TreeSetsorted order: [a, b, c]
Only LinkedHashSet keeps the order in which elements arrived.

2Using It to Deduplicate While Keeping Order

The most common use is removing duplicates from a list without scrambling it.

Java
List<String> tags = List.of("java", "spring", "java", "kafka", "spring");
Set<String> unique = new LinkedHashSet<>(tags);
unique; // [java, spring, kafka]: first occurrences, original order
new HashSet<>(tags); // for example [spring, java, kafka]: order not defined
unique.add("java"); // false: already present
unique; // [java, spring, kafka]: re-adding does not move it

Notice the last two lines. Adding an element that is already in the set returns false and leaves its position unchanged, because the underlying map only replaces the value of an existing key; it does not unlink and re-append the entry. So the set records the order of first insertion, which is exactly what deduplication needs.

3What It Costs

The extra order is not free. Each entry of a LinkedHashMap is a HashMap node plus two more references, before and after, which adds 8 bytes per element with compressed references and usually moves the node from 32 to 40 bytes. For a set of a few thousand elements this is irrelevant; for tens of millions, it is worth counting. Iteration, on the other hand, is a little cheaper than in a HashSet, because it walks the list of entries rather than every slot of the table, including the empty ones.

LinkedHashSet is not thread-safe, for the same reason as HashSet: its HashMap and linked list have no locking. Concurrent modification can corrupt both. For shared use, we wrap it with Collections.synchronizedSet or guard it with our own lock, since the JDK has no concurrent insertion-ordered set.

4What Java 21's SequencedSet Added

Before Java 21, getting the first element of a LinkedHashSet meant set.iterator().next(), and getting the last meant iterating through the whole set. Java 21 introduced sequenced collections (JEP 431): SequencedCollection is an interface for collections with a defined encounter order, and SequencedSet is its set version. LinkedHashSet now implements SequencedSet, so it gains direct methods for both ends.

Java
LinkedHashSet<String> recent = new LinkedHashSet<>(List.of("home", "shoes", "bags"));
recent.getFirst(); // home
recent.getLast(); // bags
recent.reversed(); // [bags, shoes, home]: a reversed view, not a copy
recent.addLast("home"); // moves the existing "home" to the end
recent; // [shoes, bags, home]
recent.addFirst("hats"); // new element inserted at the front
recent; // [hats, shoes, bags, home]
recent.removeFirst(); // hats
recent.removeLast(); // home
recent; // [shoes, bags]

The key detail is the difference between add and addLast. add keeps an existing element where it is, while addFirst and addLast move an existing element to that end. That makes a recently viewed list easy: every time a user views a product, addLast(product) moves it to the most recent position, and when the list is too long, removeFirst() drops the oldest. reversed() returns a view, so changes to the set show through it and it costs nothing to create.

5Follow-up questions

When would you choose LinkedHashMap with access order instead?

When we want a cache that evicts the least recently used entry. new LinkedHashMap<>(16, 0.75f, true) reorders entries on every get, and overriding removeEldestEntry evicts automatically. LinkedHashSet has no access-order mode, so for an LRU of keys only, an access-ordered LinkedHashMap or the Java 21 addLast trick works.

Does getFirst on an empty LinkedHashSet return null?

No, it throws NoSuchElementException, like removeFirst and the Deque methods of the same names. That makes the empty case explicit instead of returning a null that could be confused with a null element.

Is LinkedHashSet ordered or sorted?

Ordered, not sorted. Its order is the order of insertion, possibly adjusted with addFirst and addLast. A TreeSet is sorted by comparison. The terms are often mixed up in interviews, and the difference matters when choosing a class.

6Conclusion

In this answer, we saw that LinkedHashSet keeps insertion order through a linked list threaded through a LinkedHashMap's entries, while keeping O(1) add, remove and contains, which makes it the natural tool for deduplicating while preserving order. Re-adding an existing element does not move it. It costs two extra links per entry and is not thread-safe. Since Java 21 it is a SequencedSet with getFirst, getLast, removeFirst, removeLast and reversed, plus addFirst and addLast, which move an existing element to that end.

What to say in the interviewAbout 80 seconds aloud

Open with

I use LinkedHashSet when I need uniqueness and a predictable order, usually insertion order. A typical case is deduplicating a list while keeping the first occurrences in their original order: new LinkedHashSet of the list does it in one line, where a HashSet would scramble the order.

Then, if they want more

It is a HashSet backed by a LinkedHashMap, so add, remove and contains stay O(1), and a doubly linked list through the entries gives the iteration order. Re-adding an element that is already present returns false and does not change its position.

The cost is memory, two extra references per entry, so roughly 8 more bytes each, and like HashSet it is not thread-safe. Java 21, with JEP 431, made it a SequencedSet. Before that, getting the last element meant iterating the whole set. Now it has getFirst, getLast, removeFirst, removeLast, and reversed, which is a view.

It also has addFirst and addLast, and the interesting difference is that these move an existing element to that end, while plain add leaves it in place. That makes a recently viewed list easy: addLast on every view, removeFirst when it gets too long. The get and remove methods throw NoSuchElementException on an empty set.

About this answer

Last updated
12 November 2026
Versions it names
Java 21
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "When would you use LinkedHashSet, what is its cost, and what did Java 21's SequencedSet...": https://scrivio-interview-library.netlify.app/java/sets/efe20ddf2d/