Java Reference
In-Depth Information
1.2.3. From passing methods to lambdas
Passing methods as values is clearly useful, but it's a bit annoying having to write a definition for
short methods such as isHeavyApple and isGreenApple when they're used perhaps only once or
twice. But Java 8 has solved this too. It introduces a new notation (anonymous functions, or
lambdas) that enables you to write just
filterApples(inventory, (Apple a) -> "green".equals(a.getColor()) );
or
filterApples(inventory, (Apple a) -> a.getWeight() > 150 );
or even
filterApples(inventory, (Apple a) -> a.getWeight() < 80 ||
"brown".equals(a.getColor()) );
So you don't even need to write a method definition that's used only once; the code is crisper
and clearer because you don't need to search to find the code you're passing. But if such a
lambda exceeds a few lines in length (so that its behavior isn't instantly clear), then you should
instead use a method reference to a method with a descriptive name instead of using an
anonymous lambda. Code clarity should be your guide.
The Java 8 designers could almost have stopped here, and perhaps they would have done so
before multicore CPUs! Functional-style programming as presented so far turns out to be
powerful, as you'll see. Java might then have been rounded off by adding filter and a few friends
as generic library methods, such as
static <T> Collection<T> filter(Collection<T> c, Predicate<T> p);
So you wouldn't even have to write methods like filterApples because, for example, the previous
call
filterApples(inventory, (Apple a) -> a.getWeight() > 150 );
could simply be written as a call to the library method filter:
filter(inventory, (Apple a) -> a.getWeight() > 150 );
 
Search WWH ::




Custom Search