Search code examples
javacomparable

Min / max function of two Comparables


I need to find the smaller of two Comparable values:

Comparable<C> a = ...;
Comparable<C> b = ...;
Comparable<C> min = a.compareTo(b) <= 0 ? a : b;

This is similar to Math.min(a, b), but for Comparable.

I know that the ternary operator is already quite short, but I can't inline the expressions for a and b and I think that min(a, b) and max(a, b) is easier to understand.

I know that there are several functions that operate on Stream and Collection values, like:

Stream.of(a, b).min(Comparator.naturalOrder())

This would help to inline the expressions, but I still find it difficult to read and a bit too much overhead for such a small task.

For the moment I'm using my own utility function, but I'm interested to know if there's an existing function for this purpose. How can one find the minimum of two Comparable values in a readable and library-independent manner without too much performance overhead?


Solution

    1. From java.util.Collections: Collections.max() and Collections.min()

      Comparable<C> a = ...;
      Comparable<C> b = ...;
      Comparable<C> min = Collections.min(Arrays.asList(a,b));
      

    1. From org.apache.commons.lang3.ObjectUtils : ObjectUtils.max() and ObjectUtils.min()

      Comparable<C> a = ...;
      Comparable<C> b = ...;
      Comparable<C> min = ObjectUtils.min(a, b);
      

    Apache Commons has less overhead and is able to handle null values, but it is a third party library.