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,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public interface Output {
public void print(String x);
}
public interface Output { public void print(String x); }
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
s -> System.out.println(s);
s -> System.out.println(s);
s -> System.out.println(s);

Notice that the parenthesis around parameter is not required when there is a single one.
[the_ad id=”651″] Multiple parameters
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,

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public interface Operation {
public int add(int x, int y);
}
public interface Operation { public int add(int x, int y); }
public interface Operation {

  public int add(int x, int y);

}

Above interface abstract method expects 2 parameters.
Below is its lambda expression implementation

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
(a, b) -> return a + b;
(a, b) -> return a + b;
(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.

Categorized in:

Java 8,