lambda表达式中的方法引用
主要有三种语法格式:
- 对象::实例方法名
- 类::静态方法名
- 类::实例方法名
1.方式一
Employee 类
@Data
@AllArgsConstructor
public class Employee {
private String name;
private Integer age;
private double salary;
}
方法引用
@Test
public void test2(){
Employee employee = new Employee("张三",10,2000);
//原来的方法
Supplier<String> supplier = ()->employee.getName();
String s = supplier.get();
//方法引用
Supplier<String> supplier1 = employee::getName;
String s1 = supplier1.get();
System.out.println(s1);
}
2.方式二
@Test
public void test1() {
//原始方法
Consumer consumer = (x)->System.out.println();
//方法引用
PrintStream out = System.out;
Consumer consumer1 = out::println;
Consumer consumer2 =System.out::println;
}
@Test
public void test3(){
//原来的方法
Comparator<Integer> comparator = (x,y)->Integer.compare(x,y);
//方法引用
Comparator<Integer> comparator1 = Integer::compare;
int compare = comparator1.compare(2, 5);
System.out.println(compare);
}
3.方式三
@Test
public void test4(){
//原来的方法
BiPredicate<String,String> biPredicate = (x,y)->x.equals(y);
boolean test = biPredicate.test("aa", "bb");
System.out.println(test);
//方法引用
BiPredicate<String,String> predicate =String::equals;
boolean test1 = predicate.test("aa", "vv");
System.out.println(test1);
}