1. What is a lambda expression?
- JDK1.8 began to support lambda expressions, which makes programming more elegant
- Use lambda to more concisely realize the declaration and invocation of anonymous inner classes and functions
- Provides stream processing based on lambda, which greatly simplifies the operation of collections
2. Comparison with traditional code
Three, basic grammar
(Parameter list) -> Implementation statement
Parameter list : Use commas to separate parameters, parameter types can be omitted, single parameter brackets can be omitted
Implementation statement : write directly on a single line, wrap multiple lines with {}
note:
Lambda expressions can only implement interfaces that have and only one abstract method. Java calls them "functional interfaces"
Implementation code:
public interface Lambda {
public float operator(int a, int b);
}
public class LambdaSample {
public static void main(String[] args) {
// 标准写法
Lambda addition = (a, b) -> {
System.out.println("加法运算");
return a + b;
};
System.out.println(addition.operator(3, 4));
// 简洁写法
Lambda subtruction = (a, b) ->
a - b;
System.out.println(subtruction.operator(4, 3));
}
};