lamda expression -- method reference
As mentioned in the previous article, lamda body is the implementation of functional interface methods. In the method body, we may refer to other methods to implement logic, so in lamda body, we can directly refer to the method of the generator
I object:: instance method name
/** * Object:: instance method name */ @Test public void test6() { Consumer<String> consumer = (x) -> System.out.println(x); consumer.accept("->"); Consumer<String> consumer1 = System.out::println; consumer1.accept("::"); }
Result:
Class II Name:: static method name
/** * Class name:: static method name */ @Test public void test7() { Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y); Comparator<Integer> comparator1 = Integer::compare; }
Class III Name:: instance method name
/** * Class name:: instance method name */ public void test8() { BiFunction<String, String, Boolean> biFunction = (x, y) -> x.equals(y); BiFunction<String, String, Boolean> biFunction1 = String::equals; }
Conclusion: 1. The reference method is consistent with the input and output parameters of the abstract method in the functional interface
2. When the third lamda expression is used, it can only be used when the input parameter can only be 2 and the first parameter in the parameter list is an instance of the class, and the second parameter in the parameter list is an instance method parameter
I,II only need to meet conclusion 1, III need to meet both conclusion 1 and conclusion 2
Lamda expression -- constructor reference
/** * Class name:: constructor */ @Test public void test9() { Supplier<Student> studentSupplier = Student::new; System.out.println("Supplier:" + studentSupplier.get()); Function<String, Student> function = Student::new; System.out.println("Function:" + function.apply("Li Si")); BiFunction<Integer, Double, Student> biFunction = Student::new; System.out.println("BiFunction:" + biFunction.apply(10, 150.0)); }
Result:
Supplier:Student{name='null', age=null, hight=null} Function:Student{name='Li Si', age=null, hight=null} BiFunction:Student{name='null', age=10, hight=150.0} Process finished with exit code 0
The constructor follows conclusion 1 (the reference method is consistent with the input and output parameters of the abstract method in the functional interface). It matches the construction method according to the number of parameters of the construction method
Personal learning
Reference resources: https://www.bilibili.com/video/av62117143