What is lamda expression and purpose of lamda expression?
- Lamda expression is a function with no name, no class, no scope and no return type declaration. Lamda expression can be defined as an anonymous function, it can be passed like argument for onother function.
- Why do we use lamda expression?
+ It provides an implementation of functional interface and support functional programming.
+ Help developer write less code and the code can be more readable
+ It’s used in Stream API
- There is a noticable point in lamda expression is that lamda expression cannot change the value of outside variable
Example:
import java.util.Arrays;
import java.util.List;
public class LambdaExample {
public static void main(String[] args) {
// List of integers
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Using lambda expression to print each number
numbers.forEach(number -> System.out.println(number));
}
}