Java Reference
In-Depth Information
3.7.4. Step 4: Use method references
We explained that method references are syntactic sugar for lambda expressions that forwards
their arguments. You can use a method reference to make your code slightly less verbose
(assuming a static import of java.util.Comparator.comparing):
inventory.sort(comparing(Apple::getWeight));
Congratulations, this is your final solution! Why is this better than code prior to Java 8? It's not
just because it's shorter; it's also obvious what it means, and the code reads like the problem
statement “sort inventory comparing the weight of the apples.”
3.8. Useful methods to compose lambda expressions
Several functional interfaces in the Java 8 API contain convenient methods. Specifically, many
functional interfaces such as Comparator, Function, and Predicate that are used to pass lambda
expressions provide methods that allow composition. What does this mean? In practice it means
you can combine several simple lambda expressions to build more complicated ones. For
example, you can combine two predicates into a larger predicate that performs an or operation
between the two predicates. Moreover, you can also compose functions such that the result of
one becomes the input of another function. You may wonder how it's possible that there are
additional methods in a functional interface. (After all, this goes against the definition of a
functional interface!) The trick is that the methods that we'll introduce are called default
methods (that is, they're not abstract methods). We explain them in detail in chapter 9 . For now,
just trust us and read chapter 9 later when you want to find out more about default methods and
what you can do with them.
3.8.1. Composing Comparators
You've seen that you can use the static method Comparator.comparing to return a Comparator
based on a Function that extracts a key for comparison as follows:
Comparator<Apple> c = Comparator.comparing(Apple::getWeight);
Reversed order
What if you wanted to sort the apples by decreasing weight? There's no need to create a different
instance of a Comparator. The interface includes a default method reverse that imposes the
 
Search WWH ::




Custom Search