Coding in the small with Google Collections: Comparators.max
Part 3 in a Series.Comparators.max takes two Comparables and returns the larger of the two. It improves upon the standard approach, which requires both a comparison and a ternary:
Before:
public Money calculateDeliveryCharge(Order order) {
double distanceInKm = Geography.getDistance(
storeAddress, order.getAddress());
Money perKm = pricePerKm.times(distanceInKm);
return perKm.compareTo(minimumDeliveryCharge) > 0
? perKm
: minimumDeliveryCharge;
}
After:
public Money calculateDeliveryCharge(Order order) {
double distanceInKm = Geography.getDistance(
storeAddress, order.getAddress());
Money perKm = pricePerKm.times(distanceInKm);
return Comparators.max(perKm, minimumDeliveryCharge);
}
Of course the Comparators.min method is also included. As a special treat, there's overloaded versions of each that allow you to specify your own comparator, such as
String.CASE_INSENSITIVE_ORDER
.Part 4