Java : Comparable with Examples

Comparable (Java SE 21 & JDK 21) with Examples.
You will find code examples on most Comparable<T> methods.


Summary

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

Class diagram

See also : Comparator

// The String class implements the Comparable interface.
final Comparable<String> comparable = "bbb";

System.out.println(comparable.compareTo("aaa")); // 1
System.out.println(comparable.compareTo("bbb")); // 0
System.out.println(comparable.compareTo("ccc")); // -1
final var list = List.of("ddd", "bbb", "ccc", "aaa");
System.out.println(list); // [ddd, bbb, ccc, aaa]

final var sorted = list.stream().sorted().toList();
System.out.println(sorted); // [aaa, bbb, ccc, ddd]

Methods

int compareTo (T o)

Compares this object with the specified object for order.

// The String class implements the Comparable interface.
final var list = List.of("ddd", "bbb", "ccc", "aaa");
System.out.println(list); // [ddd, bbb, ccc, aaa]

final var sorted = list.stream().sorted().toList();
System.out.println(sorted); // [aaa, bbb, ccc, ddd]
record Sample(String text, int num) implements Comparable<Sample> {
    @Override
    public String toString() {
        return "(%s, %d)".formatted(text, num);
    }

    @Override
    public int compareTo(Sample o) {
        if (!text.equals(o.text())) {
            return text.compareTo(o.text());
        } else {
            return num - o.num();
        }
    }
}

final var list = List.of(
        new Sample("bbb", 2), new Sample("bbb", 3), new Sample("bbb", 1),
        new Sample("aaa", 3), new Sample("aaa", 1), new Sample("aaa", 2)
);

// [(bbb, 2), (bbb, 3), (bbb, 1), (aaa, 3), (aaa, 1), (aaa, 2)]
System.out.println(list);

final var sorted = list.stream().sorted().toList();

// [(aaa, 1), (aaa, 2), (aaa, 3), (bbb, 1), (bbb, 2), (bbb, 3)]
System.out.println(sorted);

Related posts

To top of page