Lambda expressions in Java 8 are essentially unnamed functions without return types or access modifiers. They’re also known as anonymous functions or closures. Let’s explore Java 8 lambda expressions with examples.
Example 1:
public void m() {
System.out.println("Hello world");
}
Can be express as:
Java 8 Lambda Expressions with Examples
() -> {
System.out.println("Hello world");
}
//or
() -> System.out.println("Hello world");
Example 2:
public void m1(int i, int j) {
System.out.println(i + j);
}
Can be expressed as:
(int i, int j) -> {
System.out.println(i + j);
}
If the type of the parameters can be inferred by the compiler based on the context, we can omit the types. The above lambda expression can be rewritten as:
(i, j) -> System.out.println(i+j);
Example 3:
Consider the following transformation:
public String str(String s) {
return s;
}
can be expressed as:
(String s) -> return s;
or
(String s) -> s;
Conclusion:
- A lambda expression can have zero or more arguments (parameters).
- Example:
() -> System.out.println("Hello world");
(int i) -> System.out.println(i);
(int i, int j) -> System.out.println(i + j);
2. We can specify the type of the parameter. If the compiler can infer the type based on the context, then we can omit the type.
Example:
(int a, int b) -> System.out.println(a + b);
(a, b) -> System.out.println(a + b);
3. If multiple parameters are present, they should be separated by a comma (,).
4. If no parameters are present, we use empty parentheses [ like ()
].
Example:
() -> System.out.println("hello");
5. If only one parameter is present and if the compiler can infer the type, then we can omit the type and parentheses.
- Example:
6. Similar to a method body, a lambda expression body can contain multiple statements. If there are multiple statements, they should be enclosed in curly braces {}
. If there is only one statement, curly braces are optional.
7. Once we write a lambda expression, we can call that expression just like a method. To do this, functional interfaces are required.
This covers the basics of lambda expressions using in java 8 with relevant examples.
For more information, follow this link: Oracle’s guide on lambda expressions.