Collections: a TreeSet built with a Comparator drops "equal" elements as duplicates

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.

Code
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());
Output
Only the first 3-letter word is kept: [cat]
Size: 1
Advertisement
More in 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-09-27

© Java Coding Hub · About · Contact · Privacy · Terms