Skip to content
Veltoryx Technologies
ProLesson 7.7Intermediate3 min readUpdated 30 October 2026

Comparable vs Comparator

Sort your own objects with a natural order (Comparable) or any custom order (Comparator), and chain comparators the modern way.

Java can sort numbers and strings out of the box. To sort your own objects, such as products by price or students by marks then name, you tell Java how to compare them. There are two ways.

01Comparable: the natural order

A class implements Comparable<T> to define its one natural order. compareTo returns a negative number, zero or a positive number, meaning "less than", "equal" or "greater than":

ComparableDemo.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

record Version(int major, int minor) implements Comparable<Version> {
    @Override
    public int compareTo(Version other) {
        if (major != other.major) {
            return Integer.compare(major, other.major);
        }
        return Integer.compare(minor, other.minor);
    }
}

public class ComparableDemo {
    public static void main(String[] args) {
        List<Version> versions = new ArrayList<>(List.of(
                new Version(21, 0), new Version(17, 4), new Version(21, 2), new Version(8, 0)));
        Collections.sort(versions);          // uses compareTo
        System.out.println(versions);
        System.out.println(Collections.max(versions));
    }
}
Expected output
[Version[major=8, minor=0], Version[major=17, minor=4], Version[major=21, minor=0], Version[major=21, minor=2]]
Version[major=21, minor=2]

Loading the rest of the lesson…