Java Reference
In-Depth Information
1.2.2. Passing code: an example
Let's look at an example (discussed in more detail in chapter 2 , “Passing code with behavior
parameterization”) of how this helps you write programs. All the code for the examples is
available on the topic's GitHub page ( https://github.com/java8/ ). Suppose you have a class
Apple with a method getColor and a variable inventory holding a list of Apples; then you might
wish to select all the green apples and return them in a list. The word filter is commonly used to
express this concept. Before Java 8, you thus might write a method filterGreenApples:
But next, somebody would like the list of heavy apples (say over 150 g), and so, with a heavy
heart, you'd write the following method to achieve this (perhaps even using copy and paste):
We all know the dangers of copy and paste for software engineering (updates and bug fixes to
one variant but not the other), and hey, these two methods vary only in one line: the highlighted
condition inside the if construct. If the difference between the two method calls in the
highlighted code had been simply as to what weight range was acceptable, then you could have
just passed lower and upper acceptable weights as arguments to filter—perhaps (150, 1000) to
select heavy apples (over 150 g) or (0, 80) to select light apples (under 80 g).
But as we mentioned previously, Java 8 makes it possible to pass the code of the condition as an
argument, thus avoiding code duplication of the filter method. You can now write this:
 
Search WWH ::




Custom Search