Ch. 7 · Java

Java Comparators and Ordered Collections

Java Comparators and Ordered Collections. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

Comparators define ordering and equality-like behavior in sorted collections. Returning zero can make distinct values occupy the same ordering position.

Before you start

You should know Java classes, methods, collections and exceptions. Trace object identity separately from the contents of an object. For concurrent examples, state which thread owns or shares the data; a single successful execution is not proof that every interleaving is safe.

The practical goal is to reason through this situation: A TreeSet ordered only by age may retain one of two people with the same age. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: Define complete ordering

Decide which fields break ties between distinct people.

Step 2: Avoid arithmetic overflow

Use comparison helpers instead of subtracting potentially extreme integers.

Step 3: Understand sorted identity

Comparator zero means an equivalent ordering position in TreeSet.

Worked scenario

A TreeSet ordered only by age may retain one of two people with the same age.

var order = java.util.Comparator.comparingInt(Person::age)
    .thenComparing(Person::id);
java

Person is an application-defined type exposing age and id. The second comparison retains different people of the same age; without it, TreeSet can treat those people as duplicates under its ordering.

Common mistake

Subtraction-based comparisons can overflow for extreme integers.

Verify the behavior

Test equal ages, different IDs and integer extremes; verify intended set membership.

Interview exercise

Order people without losing ties.

Answer and reasoning

Use comparison helpers and a stable secondary key; align comparator behavior with the intended collection semantics.

Continue learning

Compare the scenario with the Java interview questions and test your understanding with the Java MCQs. For terminology and implementation details, consult the reference material.

More in Java

read ✓Java · hard

Java Time Types and Zone-Aware Decisions

Java Time Types and Zone-Aware Decisions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
read ✓Java · hard

Java Generics Wildcards and PECS

Use ? extends T for producers and ? super T for consumers, and understand why List<String> is not a List<Object>.

~2 min readread →
read ✓Java · easy

Java ArrayList Capacity and Performance

Java ArrayList Capacity and Performance. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc