-2

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;
DerBenniAusA
  • 727
  • 1
  • 7
  • 13
  • 2
    Can you use [`BigDecimal.max`](https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#max(java.math.BigDecimal))? – khelwood Mar 14 '19 at 14:44
  • As khelwood already suggested `BigDecimal.max(...)` would be the way to go. In fact, the source is very similar to your code: `public BigDecimal max(BigDecimal val) { return (compareTo(val) >= 0 ? this : val); }` – Thomas Mar 14 '19 at 14:46
  • Note that your code has one difference to `otherValue.max(min)`: when the comparison yields 0 your code would return `min` while `otherValue.max(min)` would return `otherValue`. Numerically they both represent the same value but they are _not_ equal, e.g. if min would be `2.00` and `otherValue` would be `2.0` (same numeric value but different scale) - so if you are ok with that then use `otherValue.max(min)`, otherwise you could roll your own version of `max(...)`. – Thomas Mar 14 '19 at 14:52

1 Answers1

3

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).)

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • You're welcome - Thought I'd just fix the typo instead of making a fuss :) – Thomas Mar 14 '19 at 14:48
  • I'd suggest adding one information for completeness: there is a difference between the OP's code and `BigDecimal.max` which _might_ be relevant - see my comment on the question. You're free to copy - I'll delete it afterwards ;) – Thomas Mar 14 '19 at 14:54
  • 1
    @Thomas I've added a note about that detail: feel free to leave your more thorough comment in place. – khelwood Mar 14 '19 at 15:00
  • 1
    Ok, I'll leave it there. If I could you'd get another +1 for the alternative :) – Thomas Mar 14 '19 at 15:17