Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Comparable.compareTo()

Defines the natural order of a class — used by sort() and TreeSet.

Available since: Java 1.2

Syntax

int compareTo(T o)

Parameters

ParameterTypeDescription
oTThe object to compare this one with.

Return value

intA negative number if this object is smaller, 0 if equal, a positive number if larger.

Examples

A record with a natural order by price:

record Product(String name, double price) implements Comparable<Product> {
    @Override
    public int compareTo(Product other) {
        return Double.compare(price, other.price);
    }
}
 
void main() {
    var products = new ArrayList<>(List.of(
            new Product("Tea", 4.5),
            new Product("Coffee", 7.0),
            new Product("Water", 1.2)));
    Collections.sort(products);
    products.forEach(p -> IO.println(p.name()));
}

Output:

Water
Tea
Coffee

Notes

Use Integer.compare(a, b) and Double.compare(a, b) instead of subtracting a - b: subtracting large numbers overflows and gives the wrong sign. String, number wrappers and LocalDate already implement Comparable.

If you need several orders (by name, by price), the class implements one Comparable and the others are expressed with a Comparator.

See also

Related recipes

In the tutorial

  • Sorting and comparators — Sorting collections in Java: natural order, reverse order, the Comparable interface, Comparator.comparing and sorting by several fields.

Thanks for reading!

Donate to the site — we work hard for you.