Java Lambda expression
A lambda expression in java is an implementation of a functional interface.
A functional interface is an interface which has ONLY 1 abstract method. It can have any number of default or static methods.
Lambda expression parameters
A lambda expression can have 1 or more than one parameters, if the functional interface method that it implements accepts parameters. Example,
public interface Output { public void print(String x); }
In above code Output
is a functional interface having only 1 abstract method print()
, which expects 1 parameter.
Below is its implementation as a lambda expression
s -> System.out.println(s);
Notice that the parenthesis around parameter is not required when there is a single one.
A lambda expression can have more than one and any number of parameters.
The number of parameters depends on the signature of interface method that it implements. Example,
public interface Operation { public int add(int x, int y); }
Above interface abstract method expects 2 parameters.
Below is its lambda expression implementation
(a, b) -> return a + b;
Note that if there are multiple parameters in a lambda expression, then,
1. they must be enclosed between parenthesis.
2. they must be separated with a comma.
3. data types of those parameters are not required since they are inferred from the interface method declaration.
Following these rules, we can pass multiple parameters in a lambda expression in java 8.