JDK-8356995 : Provide default methods min(T, T) and max(T, T) in Comparator interface
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.util
  • Priority: P4
  • Status: New
  • Resolution: Unresolved
  • Submitted: 2025-05-14
  • Updated: 2025-05-31
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 26
26Unresolved
Related Reports
CSR :  
Relates :  
Description
While we have Stream.min/max and Collections.min/max, often it's required to select a bigger or smaller object of two. Doing this with existing APIs is unnecessarily complicated. E.g., given two objects a and b and a comparator comp, we have the following possibilities to find the maximal object:

comp.compare(a, b) > 0 ? a : b
Stream.of(a, b).max(comp).get()
BinaryOperator.maxBy(comp).apply(a, b)

All of them are too wordy for such a simple operation, not very readable and confusing. Also, Stream version may have a significant performance overhead. It's suggested therefore to extend the Comparator interface adding two default methods:

public interface Comparator<T> {
...
    default T max(T a, T b) {
        return compare(a, b) > 0 ? a : b;
    }

    default T min(T a, T b) {
        return compare(a, b) > 0 ? b : a;
    }
}

In this case, the operation to select the biggest value between a and b, according to the comp comparator would be straightforward:

comp.max(a, b)

Such methods are similar to existing Math.max methods for numbers, thus fit the standard library nicely.

A similar enhancement was proposed previously (JDK-4254492) for comparable objects, but it was created before we had default methods.
Comments
A pull request was submitted for review. Branch: master URL: https://git.openjdk.org/jdk/pull/25297 Date: 2025-05-19 07:25:17 +0000
19-05-2025