Skip to content

Comparator & Sorting

The Course
•
15 min study

Ordering is a policy, not a property that a list guesses. A Comparator compares two values: negative means first before second, zero means tied, and positive means first after second. Write deterministic tie-breakers when the report must not depend on arrival order.

Work through the example

Comparator.comparingInt accepts a function that extracts an int key. String::length supplies the existing length method. thenComparing adds a second comparison when lengths tie. String::compareTo uses the string's natural lexicographic order.

These are instance-method references, unlike the static Main::positive from the lambdas lesson. String::length means text -> text.length(). In the two-argument comparator position, String::compareTo means (left, right) -> left.compareTo(right). Its result follows the negative/zero/positive ordering rule, not a boolean. For the plain capitalized words here, lexicographic order matches familiar alphabetical order; it is case-sensitive, not a locale-aware dictionary sort.

The next example's (left, right) -> { ... } has two parameters, so parentheses are required, and its block returns an int explicitly. Integer.compare(a, b) supplies the same negative/zero/positive contract for numbers.

sort changes the list in place. Copy first when you must preserve the input order. Do not compare int keys by subtracting them: subtraction can overflow for extreme values. Use Integer.compare or the comparator builders. The builders also make the intended keys visible to a reader.

Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.

Predict, then run Java
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        List<String> original = new ArrayList<>();
        original.add("Test");
        original.add("Go");
        original.add("Read");
        List<String> ordered = new ArrayList<>(original);
        Comparator<String> byLength = Comparator.comparingInt(String::length);
        ordered.sort(byLength.thenComparing(String::compareTo));
        System.out.println(ordered);
        System.out.println(original);
    }
}
Check your prediction
Text
[Go, Read, Test]
[Test, Go, Read]

Compare the behavior

An explicit comparator is sometimes easier to trace. Compare the numeric keys, and only if they tie compare the text. The comparator must agree with itself across calls; it must not change the objects or depend on a counter that changes each time.

Trace the changed case Java
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        Comparator<String> byLengthThenText = (left, right) -> {
            int order = Integer.compare(left.length(), right.length());
            if (order != 0) {
                return order;
            }
            return left.compareTo(right);
        };
        System.out.println(byLengthThenText.compare("Go", "Read") < 0);
        System.out.println(byLengthThenText.compare("Read", "Test") < 0);
        System.out.println(byLengthThenText.compare("Read", "Read") == 0);
    }
}
Check your prediction
Text
true
true
true

Trace the primary key before the tie-breaker

A comparator is called for many pairs while sorting; it does not receive a whole report at once. For Read versus Test, length comparison gives zero, so text decides their order. For Go versus Read, the differing lengths decide immediately and the secondary comparison is irrelevant.

Reversing a complete comparator reverses every decision, including ties. If the requirement is descending length and ascending text, reverse the length comparator first, then attach the text tie-breaker. Use a case containing equal lengths and a case containing unequal lengths; one cannot prove the other rule.

Comparison equality means tied for this ordering, not necessarily equal under Object.equals. A by-length comparator can tie Read and Test even though they are different strings. This course uses explicit tie-breakers for deterministic reports rather than confusing a sorting policy with value identity.

Practice independently

Exercise

Comparator & Sorting: practice

Sort a copied list of strings by descending length, then ascending text. Source: Go, Test, Read. Output must be [Read, Test, Go], while the original stays [Go, Test, Read]. Reverse only the length comparator before adding the tie-breaker; reversing the whole chain also reverses text order.

Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.

Your workspace Java
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        System.out.println("Sort a copy with an explicit tie-breaker");
    }
}
Hint 1: the idea

The primary direction and the tie-breaker's direction are separate requirements.

Hint 2: a first step

Create Comparator<String> byLength, call reversed on it, and then append the ascending text comparison.

Show one solution

One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?

Java
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        List<String> source = new ArrayList<>();
        source.add("Go");
        source.add("Test");
        source.add("Read");
        List<String> result = new ArrayList<>(source);
        Comparator<String> byLength = Comparator.comparingInt(String::length);
        result.sort(byLength.reversed().thenComparing(String::compareTo));
        System.out.println(result);
        System.out.println(source);
    }
}

Expected output:

Text
[Read, Test, Go]
[Go, Test, Read]

Change it and test again

Add another length-four title and a duplicate Read. Check the full order. Move reversed() to the end of the chain temporarily: which pair changes order? Restore it. The test should contain a tie or it cannot protect the tie-breaker.

Explain before moving on

What does a negative comparison result mean? Why is comparing only lengths insufficient when the report promises deterministic alphabetical ties?

Was this article helpful?

Your response is saved on this device.