Java Reference
In-Depth Information
NOTE
Although lambda method parameters require less boilerplate code than was needed previ-
ously, they are still statically typed. For the sake of readability and familiarity, you have
the option to include the type declarations, and sometimes the compiler just can't work it
out!
How to Spot a Lambda in a Haystack
There are a number of variations of the basic format for writing lambda expressions, which
are listed in Example 2-3 .
Example 2-3. Some different ways of writing lambda expressions
Runnable noArguments = () -> System . out . println ( "Hello World" );
ActionListener oneArgument = event -> System . out . println ( "button clicked" );
Runnable multiStatement = () -> {
System . out . print ( "Hello" );
System . out . println ( " World" );
};
BinaryOperator < Long > add = ( x , y ) -> x + y ;
BinaryOperator < Long > addExplicit = ( Long x , Long y ) -> x + y ;
shows how it's possible to have a lambda expression with no arguments at all. You can use
an empty pair of parentheses, () , to signify that there are no arguments. This is a lambda ex-
pression implementing Runnable , whose only method, run , takes no arguments and is a
void return type.
we have only one argument to the lambda expression, which lets us leave out the paren-
theses around the arguments. This is actually the same form that we used in Example 2-2 .
Instead of the body of the lambda expression being just an expression, in it's a full block
of code, bookended by curly braces ( {} ). These code blocks follow the usual rules that you
would expect from a method. For example, you can return or throw exceptions to exit them.
It's also possible to use braces with a single-line lambda, for example to clarify where it be-
gins and ends.
 
Search WWH ::




Custom Search