用到的对象:
package com.zwq;
import lombok.Data;
/**
* @author zhangwq
*/
@Data
public class Student {
private int id;
private String name;
private String clazz;
private int age;
private double grade;
public Student(String name, String clazz) {
this.name = name;
this.clazz = clazz;
}
public Student() {
}
}
package com.zwq;
import org.junit.Test;
import java.util.Comparator;
import java.util.function.*;
/**
* @author zhangwq
* 一、方法引用:如果Lambda体重的内容有方法已经实现了,我们可以使用'方法引用'
* 主要有三种语法格式:
* 1、对象::实例方法名
* 2、类::静态方法名
* 3、类::实例方法名
*/
public class MethodReference {
@Test
//对象::实例方法名
public void objectInstance(){
//*Lambda体调用方法的参数列表及返回值类型与函数式接口中的函数列表和返回值类型一致
//Lambda表达式写法
Consumer<Integer> con = (x) -> System.out.println(x);
//方法引用写法
Consumer<Integer> conNew = System.out::println;
con.accept(1);
conNew.accept(666);
Student student = new Student();
Supplier<Integer> sup = ()->student.getAge();
Integer age = sup.get();
System.out.println("Lambda表达式写法输出:"+age);
Supplier<Integer> supNew = student::getAge;
Integer ageNew = supNew.get();
System.out.println("新写法输出:"+ageNew);
}
@Test
//类名::静态方法名
public void classStatic(){
Comparator<Integer> comparator = (x,y)->Integer.compare(x,y);
Comparator<Integer> integerComparator = Integer::compare;
System.out.println(integerComparator.compare(1,2));
}
@Test
//类名::实例方法名
//**若Lambda参数列表中第一个参数是实例方法的调用者,第二个参数是实例方法的参数
// 可以使用ClassName::method
public void classInstance(){
BiPredicate<String,String> biPredicate = (x,y)->x.equals(y);
System.out.println("old: "+biPredicate.test("x","y"));
BiPredicate<String,String> biPredicateNew = String::equals;
System.out.println("new: "+biPredicateNew.test("0000","0000"));
}
//构造器引用
@Test
//需要调用的构造器的参数列表需要与函数式接口中抽象方法的参数列表保持一致
//ClassName::new
public void consRef(){
Supplier<Student> studentSupplier = ()->new Student();
Supplier<Student> studentSupplierNew = Student::new;
System.out.println(studentSupplierNew.get());
BiFunction<String,String,Student> biFunction = Student::new;
System.out.println(biFunction.apply("zhangsan","三班"));
}
@Test
//数组引用 Type[]::new
public void arrayRef(){
Function<Integer,String[]> function = (x) -> new String[x];
Function<Integer,String[]> functionNew = String[]::new;
System.out.println(function.apply(66).length+functionNew.apply(77).length);
}
}