Free learning recommendation: java basic tutorial
##1. Introduction to Lambda expressions
Lambda expression is a new feature of Java8 and one of the most worth learning new features in Java8. (Another new feature is flow programming.)
anonymous method. You can use this anonymous method to
implement the methods in the interface.
simplify interface implementation. There are many ways to implement interfaces, such as: ① Design the implementation class of the interface, ② Use anonymous inner classes. But ③ using lambda expression is simpler than these two methods.
can only implement functional interfaces: That is, in an interface, there is only one abstract method that the implementation class must implement.
@FunctionalInterface annotation
, used before the interface, is used to determine whether the interface is a functional interface. If it is not a functional interface, an error will be reported. The functionality is similar to @Override.
2. Lambda expression syntax
lambda expression is essentially an anonymous method, so when writing lambda expressions, no need You don't care what the method name is, and you don't need to care about the return value type. You only need to care about two parts:Parameter list
,
Method body.
Lambda表达式基础语法:(参数) ->{ 方法体}
The following defines 6 types offunctional interfaces
with different parameters and return values, and uses lambda expressions to implement the methods in the interface:
#The following is the lambda expression implementation for the above six functional interfaces.Syntax simplification and advanced:/** * @Description: * @author Guoqianliang * @date 19:50 - 2021/2/15 */public class BasicSyntax { public static void main(String[] args) { // 1.实现无参数,无返回值的函数式接口 NoneReturnNoneParameter lambda1 = () -> { System.out.println("这是无参,无返回值的方法"); }; lambda1.test(); // 2.实现一个参数,无返回值的函数式接口 NoneReturnSingleParameter lambda2 = (int a) -> { System.out.println("这是一个参数,无返回值的方法,参数a:" + a); }; lambda2.test(10); // 3.实现多个参数,无返回值的函数式接口 NoneReturnMutipleParameter lambda3 = (int a, int b) -> { System.out.println("这是多个参数,无返回值的方法,参数a=" + a + ",b=" + b); }; lambda3.test(10, 20); // 4.实现无参数,有返回值有返回值的函数式接口 SingleReturnNoneParameter lambda4 = () -> { System.out.println("这是无参数,有返回值的方法,返回值是:"); return 10; }; System.out.println(lambda4.test()); // 5.实现一个参数,有返回值的函数式接口 SingleReturnSingleParameter lambda5 = (int a) -> { System.out.println("这是一个参数,有返回值的方法,返回值是:"); return a; }; System.out.println(lambda5.test(10)); // 6.实现多个参数,有返回值的函数式接口 SingleReturnMutipleParameter lambda6 = (int a, int b) -> { System.out.println("这是多个参数,有返回值的方法,返回值是:"); return a + b; }; System.out.println(lambda6.test(1, 2)); }}Copy after login
3. Function reference
Lambda expressions are to simplify the interface. In lambda expressions, more complex logic should not appear. If the logic that needs to be processed is relatively complex, a separate method will generally be written. Just reference this method directly in the lambda expression. That is,refers to an existing method so that it can replace the lambda expression to complete the implementation of the interface.
1. Static method reference
Syntax:Class::Static method
Do not add parentheses after the quoted method.
- The referenced method, parameters (number, type) and return value must be consistent with those defined in the interface.
/** * @Description: 方法引用 * @author Guoqianliang * @date 0:26 - 2021/2/16 */public class Lambda1 { private static interface Calculate { int calculate(int a, int b); } private static int calculate(int x, int y) { if (x > y) { return x - y; } else if (xCopy after login
2. Non-static method reference
Syntax:Object::Non-static method
Do not add parentheses after the quoted method.
- The referenced method, parameters (number, type) and return value must be consistent with those defined in the interface.
/** * @Description: 方法引用 * @author Guoqianliang * @date 0:26 - 2021/2/16 */public class Lambda1 { private static interface Calculate { int calculate(int a, int b); } // 非静态方法 private int calculate2(int a, int b) { if (a != b) { return a - b; } return a + b; } public static void main(String[] args) { // 非静态方法引用 Calculate calculate2 = new Lambda1()::calculate2; System.out.println(calculate.calculate(10, 20)); }}Copy after login
3. Constructor method reference
Syntax:Class name::new
You can distinguish between different constructor methods through the parameters of the methods in the interface.
- If a method defined in a functional interface is just to get an object of a class. At this point, you can use the reference to the constructor method to simplify the implementation of this method.
/** * @Description: 构造方法引用 * @author Guoqianliang * @date 11:20 - 2021/2/16 */public class Lambda2 { @FunctionalInterface private interface GetPersonWithNoneParameter { Person get(); } @FunctionalInterface private interface GetPersonWithSingleParameter { Person get(String name); } @FunctionalInterface private interface GetPersonWithMutipleParameter { Person get(String name, int age); } private static class Person { String name; int age; public Person() { System.out.println("Person类的无参构造方法执行了"); } public Person(String name) { this.name = name; System.out.println("Person类的有参构造方法执行了"); } public Person(String name, int age) { this.name = name; this.age = age; System.out.println("Person类的两个参数的构造方法执行了"); } } public static void main(String[] args) { // 1.使用lambda表达式,实现GetPersonWithNoneParameter接口 GetPersonWithNoneParameter getPerson = Person::new; // 2.使用lambda表达式,实现GetPersonWithSingleParameter接口 GetPersonWithSingleParameter getPerson2 = Person::new; // 3.使用lambda表达式,实现GetPersonWithMutipleParameter接口 GetPersonWithMutipleParameter getPerson3 = Person::new; System.out.println(getPerson.get()); System.out.println(getPerson2.get("树先生")); System.out.println(getPerson3.get("你好", 23)); }}Copy after login
4. Special references to object methods
When using lambda expressions to implement certain interfaces, if in the lambda expression Contains an object. In the method body, directly using this object to call one of its methods can complete the overall logic./** * @Description: 对象方法的特殊应用 * @author Guoqianliang * @date 11:54 - 2021/2/16 */public class Lambda3 { @FunctionalInterface private interface MyInterface { // String get(Person person); void set(Person person, String name); } private static class Person { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } } public static void main(String[] args) { Person p1 = new Person(); p1.setName("小明");// 逻辑实现只是为了获取到对象的名字// MyInterface lambda2 = Person::getName;// System.out.println(lambda2.get(p1)); // 逻辑实现只是为了给对象的某些属性进行赋值 MyInterface lambda1 = (x, n) -> x.setName(n); MyInterface lambda2 = Person::setName; lambda2.set(p1, "李华"); System.out.println(p1.getName()); }}Copy after login
4. Issues to note with Lambda expressions
Iflocal variables
are used, they will be declared by default As a constant, the value cannot change.
/** * @Description: * @author Guoqianliang * @date 13:05 - 2021/2/16 */public class Lambda4 { public static void main(String[] args) { // 1.定义一个局部变量 int x = 10; // 2.使用lambda表达式实现接口 LambdaTest lambda = () -> { System.out.println("x=" + x); }; // 3. 无法修改常量x // x=20; }}@FunctionalInterfaceinterface LambdaTest { void test();}Copy after login
Related learning recommendations: java basics
The above is the detailed content of Introducing Lambda expressions, the syntactic sugar of Java 8. For more information, please follow other related articles on the PHP Chinese website!