Coding in the small with Google Collections: Comparators.fromFunction
Part 12 in a Series.Comparators.fromFunction() allows you to create a Comparator based on the properties and attributes of a your business objects. Since the same function is applied to both of the values to compare, this method makes it easier to write a symmetric comparator:
Before:
public Comparator<Product> createRetailPriceComparator(
final CurrencyConverter currencyConverter) {
return new Comparator<Product>() {
public int compare(Product a, Product b) {
return getRetailPriceInUsd(a).compareTo(getRetailPriceInUsd(b));
}
public Money getRetailPriceInUsd(Product product) {
Money retailPrice = product.getRetailPrice();
return retailPrice.getCurrency() == CurrencyCode.USD
? retailPrice
: currencyConverter.convert(retailPrice, CurrencyCode.USD);
}
};
}
After:
public Comparator<Product> createRetailPriceComparator(
final CurrencyConverter currencyConverter) {
return Comparators.fromFunction(new Function<Product,Money>() {
/** returns the retail price in USD */
public Money apply(Product product) {
Money retailPrice = product.getRetailPrice();
return retailPrice.getCurrency() == CurrencyCode.USD
? retailPrice
: currencyConverter.convert(retailPrice, CurrencyCode.USD);
}
});
}
This makes it easy to write expressive comparators. As a special treat, there's an overloaded version of fromFunction that lets you to specify which Comparator for ordering the function's return values. For example, null is supported with Comparators.nullGreatestOrder() as the second argument. Or put the priciest products first using Collections.reverseOrder() as the second argument.
Part 13