Video in progress
In what order does TreeSet keep its elements, and what does that cost?
TreeSet always keeps elements sorted, either in natural order or by the Comparator you give it. It is backed by a red-black tree, so add, remove and contains are O(log n).
📖 Answer
Set<Integer> scores = new TreeSet<>(List.of(70, 95, 40, 88));
System.out.println(scores); // [40, 70, 88, 95]
Set<String> byLength = new TreeSet<>(Comparator.comparing(String::length));
byLength.add("olma");
byLength.add("nok");
byLength.add("anor"); // not added! same length as "olma"
Look at the last line: TreeSet decides equality by compare(...) == 0, not by equals. The comparator only looks at length, so "anor" counts as a duplicate.
Compared to HashSet: HashSet is close to O(1) but has no order. If you need sorted output, or methods like first(), last() and headSet(), use TreeSet.
Sign up to mark studied questions and save your progress.