Java Reference
In-Depth Information
You can now use the method filter with a List of bananas, oranges, Integers, or Strings! Here's
an example, using lambda expressions:
List<Apple> redApples =
filter(inventory, (Apple apple) -> "red".equals(apple.getColor()));
List<String> evenNumbers =
filter(numbers, (Integer i) -> i % 2 == 0);
Isn't it cool? You've managed to find the sweet spot between flexibility and conciseness, which
wasn't possible prior to Java 8!
2.4. Real-world examples
You've now seen that behavior parameterization is a useful pattern to easily adapt to changing
requirements. This pattern lets you encapsulate a behavior (a piece of code) and parameterize
the behavior of methods by passing and using these behaviors you create (for example, different
predicates for an Apple). We mentioned earlier that this approach is similar to the strategy
design pattern. You may have already used this pattern in practice. Many methods in the Java
API can be parameterized with different behaviors. These methods are often used together with
anonymous classes. We show three examples, which should solidify the idea of passing code for
you: sorting with a Comparator, executing a block of code with Runnable, and GUI event
handling.
2.4.1. Sorting with a Comparator
Sorting a collection is a recurring programming task. For example, say your farmer wants you to
sort the inventory of apples based on their weight. Or perhaps he changes his mind and wants
 
Search WWH ::




Custom Search