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

5 comments:

William said...

There is a small error in your post. You used the class name "Comparables" instead of the correct class name "Comparators".

swankjesse said...

Thanks! Fixed.

technophilos said...

sweet!!!

Anonymous said...

There're some "Comparables" yet.

swankjesse said...

Fixed; how embarrassing.

In other news, the 'new' new way to do this with Google Collections is even simpler with the Ordering base class. It lets you do stuff like this:
Date payday = ...
Date weekend = ...
Date party = Comparators.naturalOrder().min(payday, vacation);