Java Reference
In-Depth Information
The arrow notation -> indicates the code to execute. If it's a simple expression as here, you
can just write it as shown. If there is conditional logic or other statements, you have to use a
block, as is usual in Java.
Here I just rewrite the search example to show it as a block:
results = searchApp . search ( c -> {
iif ( c . isIlc () && c . getPrice () < 500 )
return
return true
true ;
else
return
return false
false ;
});
The first c inside the parenthesis corresponds to Camera c in the explicitly implemented
choose() method: you can omit the type because the compiler knows it! If there is more
than one argument to the method, you must parenthesize them. Suppose we had a compare
method that takes two cameras and returns a quantitative value (oh, and good luck trying to
get two photographers to agree on that algorithm!):
double
double goodness = searchApp . compare (( c1 , c2 ) -> {
// write some amazing code here
});
This notion of lambdas seems pretty potent, and it is! You will see much more of this in Java
as Java 8 moves into the mainstream of computing.
Up to here, we still have to write an interface for each type of method that we want to be able
to lambda-ize. The next recipe shows some predefined interfaces that you can use to further
simplify (or at least shorten) your code.
And, of course, there are many existing interfaces that are “functional,” such as the Ac-
tionListener interface from GUI applications. Interestingly, the IntelliJ IDE (see Compil-
ing, Running, and Testing with an IDE ) automatically recognizes inner class definitions that
are replaceable by lambdas and, when using “code folding” (the IDE feature of representing
an entire method definition with a single line), replaces the inner class with the correspond-
ing lambda! Figures 9-1 and 9-2 show a before-and-after picture of this code folding.
Search WWH ::




Custom Search