LinkedHashSet implements SequencedSet in Java 21, so it now supports addFirst, getLast and reversed() directly.
SequencedSet<String> tags = new LinkedHashSet<>(List.of("java", "spring"));
tags.addFirst("featured");
tags.addLast("kafka");
tags.addFirst("java"); // moves the existing element to the front
System.out.println(tags);
System.out.println("first = " + tags.getFirst() + ", last = " + tags.getLast());
System.out.println("reversed = " + tags.reversed());
[java, featured, spring, kafka]
first = java, last = kafka
reversed = [kafka, spring, featured, java]
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-07-30