RFR: 8356995: Provide default methods min(T, T) and max(T, T) in Comparator interface [v2]

Peter Levart plevart at openjdk.org
Wed May 21 17:26:54 UTC 2025


On Wed, 21 May 2025 09:09:15 GMT, Tagir F. Valeev <tvaleev at openjdk.org> wrote:

>> Implementation of Comparator.min and Comparator.max methods. Preliminary discussion is in this thread:
>> https://mail.openjdk.org/pipermail/core-libs-dev/2025-May/145638.html
>> The specification is mostly composed of Math.min/max and Collections.min/max specifications. 
>> 
>> The methods are quite trivial, so I don't think we need more extensive testing (e.g., using different comparators). But if you have ideas of new useful tests, I'll gladly add them.
>> 
>> I'm not sure whether we should specify exactly the behavior in case if the comparator returns 0. I feel that it could be a useful invariant that `Comparator.min(a, b)` and `Comparator.max(a, b)` always return different argument, partitioning the set of {a, b} objects (even if they are equal). But I'm open to suggestions here.
>
> Tagir F. Valeev has updated the pull request incrementally with one additional commit since the last revision:
> 
>   Return first argument in case of tie (to be consistent with BinaryOperator); junit tests

Hi,

There exists a class implementing Comparator<T> and min and max methods too. But they are generic:

https://github.com/google/guava/blob/f1b962f1f1d1c96068c62b7ff55426ea249cbd55/guava/src/com/google/common/collect/Ordering.java#L622C10-L622C79


  public <E extends T> E max(E a, E b) {
    return (compare(a, b) >= 0) ? a : b;
  }


So when I have:


Comparator<CharSequence> cmp = ...

var greatest = cmp.max("foo", "bar");


...then the type of `greatest` would be `String` and not `CharSequence`.

-------------

PR Comment: https://git.openjdk.org/jdk/pull/25297#issuecomment-2898707140


More information about the core-libs-dev mailing list