TreeSet decides uniqueness using its comparator, not equals, so a comparator that treats two different values as equal silently rejects the second one on insertion.
Comparator<String> byLength = Comparator.comparingInt(String::length);
TreeSet<String> set = new TreeSet<>(byLength);
set.add("cat");
set.add("dog");
set.add("owl");
System.out.println("Only the first 3-letter word is kept: " + set);
System.out.println("Size: " + set.size());
Only the first 3-letter word is kept: [cat]
Size: 1
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-09-27