Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

LinkedHashSet

A set that remembers the insertion order of elements.

Available since: Java 1.4

Syntax

public class LinkedHashSet<E> extends HashSet<E> implements SequencedSet<E>

Examples

Removing duplicates while keeping the order:

void main() {
    List<String> visits = List.of("home", "cart", "home", "pay", "cart");
    Set<String> pages = new LinkedHashSet<>(visits);
    IO.println(pages);
}

Output:

[home, cart, pay]

The first and the last element (Java 21):

void main() {
    var set = new LinkedHashSet<>(List.of(3, 1, 2));
    IO.println(set.getFirst() + " " + set.getLast());
    IO.println(set.reversed());
}

Output:

3 2
[2, 1, 3]

Notes

It is almost as fast as HashSet but uses a little more memory. Adding an existing element again does not change its position. Since Java 21 it implements SequencedSet, so getFirst(), getLast() and reversed() are available.

See also

  • HashSet — A set without duplicates backed by a hash table; order is not guaranteed.
  • TreeSet — A set that keeps its elements in sorted order.
  • List.getFirst() — Returns the first or the last element of an ordered collection.

Related recipes

In the tutorial

  • Sets: Set — Sets in Java: HashSet without duplicates, LinkedHashSet and TreeSet with ordering, union and intersection of sets.

Thanks for reading!

Donate to the site — we work hard for you.