Java Reference
In-Depth Information
3.7. Putting lambdas and method references into practice!
To wrap up this chapter and all we've discussed on lambdas, we continue with our initial
problem of sorting a list of Apples with different ordering strategies and show how you can
progressively evolve a naïve solution into a concise solution, using all the concepts and features
explained so far in the topic: behavior parameterization, anonymous classes, lambda
expressions, and method references. The final solution we work toward is this (note that all
source code is available on the topic's web page):
inventory.sort(comparing(Apple::getWeight));
3.7.1. Step 1: Pass code
You're lucky; the Java 8 API already provides you with a sort method available on List so you
don't have to implement it. So the hard part is done! But how can you pass an ordering strategy
to the sort method? Well, the sort method has the following signature:
void sort(Comparator<? super E> c)
It expects a Comparator object as argument to compare two Apples! This is how you can pass
different strategies in Java: they have to be wrapped in an object. We say that the behavior of
sort is parameterized : its behavior will be different based on different ordering strategies passed
to it.
Your first solution looks like this:
public class AppleComparator implements Comparator<Apple> {
public int compare(Apple a1, Apple a2){
return a1.getWeight().compareTo(a2.getWeight());
}
}
inventory.sort(new AppleComparator());
3.7.2. Step 2: Use an anonymous class
Rather than implementing Comparator for the purpose of instantiating it once, you saw that you
could use an anonymous class to improve your solution:
 
Search WWH ::




Custom Search