Min / Max function with two Comparable

  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.


3rd party solutions

Collections has max(collection) and min(collection) methods, which kind of do what you want.

Bringing whole new library just to inline one simple op might be an overkill, unless you have Apache Commons or Guava in the mix.

Hand crafted

public <T extends Comparable<T>> T max(T a, T b) { 
    return a.compareTo(b) >= 0 ? a : b; 
}

public <T extends Comparable<T>> T min(T a, T b) { 
    return a.compareTo(b) < 0 ? a : b; 
}

I have created my own helper class, which extends Comparable by min, max, isLessThan, isLessOrEqualTo, isGreaterThan and isGreaterOrEqualTo:

public interface Ordered<T> extends Comparable<T> {

  static <T extends Comparable<T>> T min(T a, T b) {
    return a.compareTo(b) <= 0 ? a : b;
  }

  static <T extends Comparable<T>> T max(T a, T b) {
    return a.compareTo(b) >= 0 ? a : b;
  }

  default boolean isLessThan(T other) {
    return compareTo(other) < 0;
  }

  default boolean isLessOrEqualTo(T other) {
    return compareTo(other) <= 0;
  }

  default boolean isGreaterThan(T other) {
    return compareTo(other) > 0;
  }

  default boolean isGreaterOrEqualTo(T other) {
    return compareTo(other) >= 0;
  }

}

The min and max methods I use for any Comparable:

String first = "a";
String second = "b";
System.out.println(Ordered.min(first, second)); // Prints "a"

For my own implementations of Comparable I extend Ordered and use that one for readable comparisons. Very helpful for enums:

public enum Board implements Ordered<Board> {
  NONE,
  BREAKFAST,
  HALF_BOARD,
  FULL_BOARD,
  ALL_INCLUSIVE
}

Usage:

Board requestedBoard = ...;
Board availableBoard = ...;
if (requestedBoard.isLessOrEqualTo(availableBoard)) {
  ...
}