Lamda表达式学习笔记二

时间:2023-03-09 16:41:55
Lamda表达式学习笔记二

Lamda表达式学习笔记二

lamda表达式----方法引用

上一篇讲到Lamda体就是对函数式接口方法的实现 ,在方法体中我们可能会引用其他方法实现逻辑,所以在lamda体中我们可以直接引用器方法

I 对象::实例方法名

/**
* 对象::实例方法名
*/
@Test
public void test6() {
Consumer<String> consumer = (x) -> System.out.println(x);
consumer.accept("->");
Consumer<String> consumer1 = System.out::println;
consumer1.accept("::");
}

结果:Lamda表达式学习笔记二

II 类名::静态方法名

 /**
* 类名::静态方法名
*/
@Test
public void test7() {
Comparator<Integer> comparator = (x, y) -> Integer.compare(x, y); Comparator<Integer> comparator1 = Integer::compare;
}

III 类名::实例方法名

/**
* 类名::实例方法名
*/
public void test8() {
BiFunction<String, String, Boolean> biFunction = (x, y) -> x.equals(y);
BiFunction<String, String, Boolean> biFunction1 = String::equals;
}

结论:1、引用的方法与函数式接口中抽象方法的入参出参保持一致

    2、使用第三种lamda表达式时,只有入参只能为2个且参数列表中第一个参数是类的实例,参数列表中第二个参数是实例方法的参数时才可以用

I,II仅需满足结论1,III需要同时满足结论1和结论2

Lamda表达式----构造器引用

/**
* 类名::构造器
*/
@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("李四"));
BiFunction<Integer, Double, Student> biFunction = Student::new;
System.out.println("BiFunction:" + biFunction.apply(10, 150.0)); }

结果:

Supplier:Student{name='null', age=null, hight=null}
Function:Student{name='李四', age=null, hight=null}
BiFunction:Student{name='null', age=10, hight=150.0} Process finished with exit code 0

构造器遵循结论1(引用的方法与函数式接口中抽象方法的入参出参保持一致),是根据构造方法的参数数量来匹配构造方法

个人学习,侵删

参考:https://www.bilibili.com/video/av62117143