Java Comparator.comparingInt and List.sort
A list of jobs can be sorted using the priority field alone. Java’s stable list sort keeps the arrival order for jobs that have the same priority.
A simple example
Comparator.comparingInt and List.sort
- Start with A with rank 2, B with rank 1, C with rank 2
- Do this Stable sort by rank
- Result B, A, C
Syntax
jobs.sort(Comparator.comparingInt(Job::priority))
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaKeep arrival order within a priority
A help desk assigns requests to priority groups. When two requests have the same priority, the staff want the one that arrived first to stay first after sorting.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
class Main {
record Job(String name, int priority) {}
public static void main(String[] args) throws Exception {
var jobs = new ArrayList<>(List.of(new Job("pack", 2), new Job("inspect", 1), new Job("ship", 2)));
jobs.sort(Comparator.comparingInt(Job::priority));
jobs.forEach(job -> System.out.println(job.name()));
}
}
inspect pack ship
List.of returns an unmodifiable list. Copy the jobs into an ArrayList before sorting, or collect a sorted stream when the original order must also remain available.
Sort a packing run from lightest to heaviest
A volunteer loads three grocery crates onto a trolley. She puts their weights in ascending order so lighter crates can be identified before the heavy ones are lifted.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
class Main {
public static void main(String[] args) throws Exception {
var weights = new ArrayList<>(List.of(8, 2, 5));
weights.sort(Comparator.naturalOrder());
System.out.println(weights.get(0) + ", " + weights.get(1) + ", " + weights.get(2));
}
}
2, 5, 8
The mutable list is reordered using the natural ordering of its integer weights.
Count packs on the delivery slip
A loading desk receives four item counts in sequence. The supervisor sorts the counts from smallest to largest. Which sequence goes on the summary sheet?
What to watch for
Sort a mutable list. A list created with List.of will reject changes.