Core Java

core28ComparatorDemo

Path
pkg1core/core28ComparatorDemo.java
Package
pkg1core
Study order
27
Run
Single-file source launch
Command
java pkg1core/core28ComparatorDemo.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg1core/core28ComparatorDemo.java
1package pkg1core;2 3/*4 * core28ComparatorDemo.java5 * -------------------------6 * Comparable (natural order) vs Comparator (custom order); chaining comparators.7 *8 * EXPLANATION:9 *  - Comparable: built into the class (`compareTo`). One natural ordering.10 *  - Comparator: external, multiple orderings, lambdas/method refs.11 *  - Use `Comparator.comparing`, `thenComparing`, `reversed`, `nullsFirst/Last`.12 */13import java.util.*;14 15public class core28ComparatorDemo {16 17    record Student(String name, int score, int age) implements Comparable<Student> {18        @Override19        public int compareTo(Student o) {20            return Integer.compare(this.score, o.score);   // natural: by score ascending21        }22    }23 24    public static void main(String[] args) {25        List<Student> list = new ArrayList<>(List.of(26                new Student("Ana", 88, 20),27                new Student("Bob", 92, 19),28                new Student("Cara", 88, 21)));29 30        // Natural order (Comparable)31        Collections.sort(list);32        System.out.println("by score (Comparable): " + list);33 34        // Custom Comparator: score desc, then age asc35        list.sort(Comparator36                .comparingInt(Student::score).reversed()37                .thenComparingInt(Student::age));38        System.out.println("score desc, age asc:   " + list);39 40        // Comparator.comparing with null-safe name41        list.sort(Comparator.comparing(Student::name, Comparator.nullsLast(String::compareTo)));42        System.out.println("by name:               " + list);43    }44}