LinkedHashSet de-duplicates like HashSet but preserves the order elements were first added - the usual choice for stable, unique output.
var seen = new LinkedHashSet<String>();
for (String s : List.of("delta", "alpha", "delta", "charlie", "alpha")) {
seen.add(s);
}
System.out.println("LinkedHashSet: " + seen);
System.out.println("TreeSet : " + new TreeSet<>(seen));
LinkedHashSet: [delta, alpha, charlie]
TreeSet : [alpha, charlie, delta]
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