Junior
What is a lambda expression in Java?
sobes.tech AI
Answer from AI
A lambda expression in Java is an anonymous function that allows you to represent instances of functional interfaces in a more concise form.
Features:
- No name: The lambda has no name; it is defined "on the fly".
- No access modifiers: It does not have
public,private, etc. - No return type: The return type is determined automatically by the compiler.
- Body: Can be an expression (no need for the
returnkeyword) or a block of code. - Parameters: Passed in parentheses, types can be omitted if the compiler can infer them.
Syntax:
parameters -> body
Examples:
- No parameters:
() -> System.out.println("Hello") - With one parameter:
x -> x * x - With multiple parameters:
(a, b) -> a + b - With explicit types:
(int x, int y) -> x + y - With a code block:
(a, b) -> { int sum = a + b; return sum; }
A functional interface is an interface with one abstract method. The lambda expression implements this abstract method.
// Example using the functional interface Runnable
Runnable myRunnable = () -> System.out.println("Running from lambda");
new Thread(myRunnable).start();
// Example using the functional interface Predicate
import java.util.function.Predicate;
Predicate<Integer> isEven = num -> num % 2 == 0;
boolean result = isEven.test(4); // true
Advantages:
- Conciseness: Reduces boilerplate code.
- Functional programming: Enables functional programming approaches (e.g., when working with Stream API).
- Readability: In some cases, makes the code more understandable, especially when passing simple logic blocks.
Lambda expressions were introduced in Java 8.