Library contents

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

  1. Start with A with rank 2, B with rank 1, C with rank 2
  2. Do this Stable sort by rank
  3. Result B, A, C
B moves to the front. A and C tie, so their original order is preserved.

Syntax

Java 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.java

Keep 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.

First output lineinspect
Main.java
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()));
    }
}
Output
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.

Advertisements

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.

Result2, 5, 8
Main.java
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));
    }
}
Output
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?

Given6 · 2 · 6 · 0
Worked result0 · 2 · 6 · 6

What to watch for

Sort a mutable list. A list created with List.of will reject changes.

Documentation for Comparator.comparingInt and List.sort