Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8356995

Provide default methods min(T, T) and max(T, T) in Comparator interface

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Unresolved
    • Icon: P4 P4
    • None
    • None
    • core-libs
    • None

      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.

            tvaleev Tagir Valeev
            tvaleev Tagir Valeev
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated: