Skip to main content
Collections framework · Topic 6 of 8

Comparable and Comparator

Definition​

Comparable gives a class its natural order through compareTo. A Comparator defines a different order from the outside, so you can sort the same objects in several ways. Comparator.comparing builds one from a field.

Example code​

Natural order, then custom orders

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

class Person implements Comparable<Person> {
final String name;
final int age;

Person(String name, int age) { this.name = name; this.age = age; }

@Override public int compareTo(Person other) { return name.compareTo(other.name); } // natural order: by name
@Override public String toString() { return name + "(" + age + ")"; }
}

class Demo {
public static void main(String[] args) {
List<Person> people = new ArrayList<>(List.of(new Person("Ravi", 30), new Person("Asha", 30), new Person("Meera", 25)));

people.sort(null); // uses compareTo
System.out.println(people);

people.sort(Comparator.comparingInt((Person p) -> p.age).thenComparing(p -> p.name)); // age, then name
System.out.println(people);

people.sort(Comparator.comparingInt((Person p) -> p.age).reversed()); // oldest first
System.out.println(people);
}
}

// Output:
// [Asha(30), Meera(25), Ravi(30)]
// [Meera(25), Asha(30), Ravi(30)]
// [Asha(30), Ravi(30), Meera(25)]

Finished this page? Track your progress (saved only in your browser).