Java Reference
In-Depth Information
// Takes no parameters and returns a string "OK"
() -> "OK"
// Takes a String parameter and prints it on the standard output
(String msg) -> { System.out.println(msg); }
// Takes a parameter and prints it on the standard output
msg -> System.out.println(msg)
// Takes a String parameter and returns its length
(String str) -> str.length()
At this point, you will not be able to understand the syntax of lambda expressions completely. I will cover the
syntax in detail shortly. For now, just get the feel of it, keeping in mind that the syntax for lambda expressions is
similar to the syntax for declaring methods.
a lambda expression is not a method, although its declaration looks similar to a method. as the name suggests,
a lambda expression is an expression that represents an instance of a functional interface.
Tip
Every expression in Java has a type; so does a lambda expression. The type of a lambda expression is a functional
interface type. When the abstract method of the functional interface is called, the body of the lambda expression is
executed.
Consider the lambda expression that takes a String parameter and returns its length:
(String str) -> str.length()
What is the type of this lambda expression? The answer is that we do not know. By looking at the lambda
expression, all you can say is that it takes a String parameter and returns an int , which is the length of the String .
Its type can be any functional interface type with an abstract method that takes a String as a parameter and returns
an int . The following is an example of such a functional interface:
@FunctionalInterface
interface StringToIntMapper {
int map(String str);
}
The lambda expression represents an instance of the StringToIntMapper functional interface when it appears in
the assignment statement, like so:
StringToIntMapper mapper = (String str) -> str.length();
In this statement, the compiler finds that the right-hand side of the assignment operator is a lambda
expression. To infer its type, it looks at the left-hand side of the assignment operator that expects an instance of the
StringToIntMapper interface; it verifies that the lambda expression conforms to the declaration of the map() method
 
 
Search WWH ::




Custom Search