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.
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 (
- csr for
-
JDK-8357219 Provide default methods min(T, T) and max(T, T) in Comparator interface
-
- Draft
-
- relates to
-
JDK-4254492 Math.min() and Math.max() extension
-
- Closed
-
- links to
-
Review(master) openjdk/jdk/25297