Java Reference
In-Depth Information
(String text) ->
{System.out.println("Hello " + text);};
// Invoke the method call
helloLambda.hello("Lambda");
}
}
Results:
Hello Lambda
How It Works
A lambda expression is an anonymous block of code that encapsulates an expression or
a series of statements and returns a result. Lambda expressions are also known as clos-
ures in some other languages. They can accept zero or more parameters, any of which
can be passed with or without type specification since the type can be automatically de-
rived from the context. While it is possible for code written in the Java language to
move forward without the use of lambda expressions, they are an important addition
that greatly improves overall maintainability, readability, and developer productivity.
Lambda expressions are an evolutionary change to the Java language, as they are an-
other step toward modernization of the language, and help keep it in sync with other
languages.
The syntax of a lambda expression includes an argument list, a new character to the
language known as the “arrow token” (->), and a body. The following model represents
the structure of a lambda expression:
(argument list) -> { body }
The argument list for a lambda expression can include zero or more arguments. If
there are no arguments, then an empty set of parentheses can be used. If there is only
one argument, then no parentheses are required. Each argument on the list can include
an optional type specification. If the type of the argument is left off, then the type is de-
rived from the current context.
In the solution for this recipe, curly braces surround the body of a block, which
contains more than a single expression. The curly braces are not necessary if the body
consists of a single expression. The curly braces in the solution could have been left
Search WWH ::




Custom Search