Saturday, June 13, 2026

Java 26: min() and max() in Comparator

Java 26 adds two small but very useful default methods to the Comparator interface: min and max.

Consider the following comparator:

Comparator<Person> ageComparator =
        Comparator.comparingInt(Person::age);

Before Java 26, finding the older of two people was awkward:

ageComparator.compare(alice, bob) > 0 ? alice : bob

// alternatively, use Stream.max:
Stream.of(alice, bob).max(ageComparator).get()

With Java 26, it becomes much cleaner:

Person older = ageComparator.max(alice, bob);
Person younger = ageComparator.min(alice, bob);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.