Search code examples
javaternary

How to simplify ternary expression


Is it possible to simplify this min + ternary expression by a one liner?

BigDecimal min = x.getMinimum();
BigDecimal result = otherValue.compareTo(min) > 0 ? otherValue : min;

Solution

  • Seems like you want BigDecimal.max.

    BigDecimal result = otherValue.max(x.getMinimum());
    

    This will give you whichever is the greater of otherValue and x.getMinimum().

    (If neither is greater than the other, it will return otherValue rather than x.getMinimum(), but that is probably close enough to what you want — the alternative would be x.getMinimum().max(otherValue).)