Finding max or min of exactly two objects
Tagir Valeev
amaembo at gmail.com
Tue May 13 14:12:21 UTC 2025
Hello!
Several times already when writing Java programs, I stumbled with a simple
task: given two objects with natural order, find the maximal of them. The
algorithm I need could be formulated like this:
<T extends Comparable<T>> T max(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
Writing manually compareTo >= 0 looks too verbose, not very readable and
error-prone: one has to mention both objects twice, and it's possible to
mix > with <. I can surely add a method mentioned above to a utility class
in my project and use it everywhere. However, I feel that it deserves a
place in the standard library.
The alternatives we have now:
BinaryOperator.maxBy(Comparator.<T>naturalOrder()).apply(a, b);
This speaks clearly about the intent (we'd like to get the maximum and we
write 'maxBy') but very wordy.
Stream.of(a, b).max(Comparator.naturalOrder()).get();
Also clear and a little bit shorter, but has an unnecessary Optional
in-between (we know that we have at least one element, so the result is
always present) and we have to mention the comparator. Finally, it might be
much less efficient than expected.
Probably we can add simple static methods `max` and `min` either to the
`Comparator` interface, or to `java.util.Objects`? Such methods would
complement methods from the `Math` class for numbers. In addition, having
default methods `max` and `min` in the `Comparator` interface would also be
nice:
String bigger = String.CASE_INSENSITIVE_ORDER.max("Hello", "world");
What do you think? Can we proceed with such an enhancement?
With best regards,
Tagir Valeev
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/core-libs-dev/attachments/20250513/29e906dd/attachment.htm>
More information about the core-libs-dev
mailing list