Java Reference ยท Collections
The LinkedHashSet class
Reference for java.util.LinkedHashSet: a set that remembers insertion order, with hash-speed lookups, sequenced-collection methods and typical uses.
LinkedHashSet<E> is a HashSet that also threads a doubly linked list through its entries. The result is a set with no duplicates, expected constant-time add, remove and contains, and a predictable iteration order: the order in which elements were first inserted.
Re-adding an element that is already present does not change its position. Because of its order guarantee it is the usual way to remove duplicates from a list while keeping the first occurrence of each item.
Set<String> unique = new LinkedHashSet<>(List.of("b", "a", "b", "c")); // [b, a, c]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public class LinkedHashSet<E> extends HashSet<E> implements SequencedSet<E>, Cloneable, java.io.Serializable
| Constructor | Description |
|---|---|
LinkedHashSet() |
Empty set. |
LinkedHashSet(int initialCapacity) |
Empty set with the given capacity. |
LinkedHashSet(int initialCapacity, float loadFactor) |
Capacity and load factor. |
LinkedHashSet(Collection<? extends E> c) |
Elements of c in its iteration order, duplicates dropped. |
| Member | Description |
|---|---|
getFirst(), getLast() |
Oldest and newest element. Throw NoSuchElementException if empty (Java 21). |
addFirst(E), addLast(E) |
Insert at an end; if the element exists it is moved there (Java 21). |
removeFirst(), removeLast() |
Remove and return an end element (Java 21). |
SequencedSet<E> reversed() |
A reverse-ordered view (Java 21). |
static <T> LinkedHashSet<T> newLinkedHashSet(int n) |
Pre-sized set (Java 19). |
Usage notes
- Order is insertion order and is not affected by re-inserting an existing element with
add(). The Java 21 methodsaddFirst/addLastdo reposition. - Cost: slightly more memory and a bit slower inserts than
HashSetbecause of the links; iteration is proportional to size, not capacity, so it can be faster thanHashSetfor sparse sets. - Equality: two sets are equal if they contain the same elements, regardless of order. A
LinkedHashSetequals aHashSetwith the same contents. - Null: one
nullis allowed. - Not synchronized, and iterators are fail-fast.
- Sequenced methods (
getFirst,reversed, ...) need Java 21 or later; on older versions use an iterator. - Not sorted. Insertion order is not sort order; use
TreeSetto sort.