方法引用主要有三类:
指向静态方法的引用 如:
指向任意类型实例的方法 如:(String s )-> s.toUppeCase()这个对象本身就是lambda的一个参数 写作String::toUpperCase
指向先有对象的实例方法的方法引用 指的是在lambda中调用一个已经存在的外部对象中的方法
如下示例,这里引用的是字符串数组中任意一个对象的compareToIgnoreCase方法。
String[] stringArray = { "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" }; Arrays.sort(stringArray, String::compareToIgnoreCase);
构造函数方法的引用
是不将构造函数实例化却能够引用它。
使用它的名称和关键字new来创建它的一个引用
Class::new 它适合Supplier接口的签名 。 ()-> Apple
Supplier<Apple> c1 = Apple::new;// 利用默认构造函数创建Apple的lambda表达式 等价于 Supplier<Apple> c1 = () -> new Apple(); c1.get();产生一个新的Apple
public void Test2() {
Function<String, Student> function1 = (name) -> new Student(name); //使用Lambda表达式
Function<String, Student> function2 = Student::new; //使用构造器引用
System.out.println(function1.apply("Moti"));
System.out.println(function2.apply("Moti"));
BiFunction<String, Integer, Student> function3 = (name,age) -> new Student(name, age);//使用Lambda表达式
BiFunction<String, Integer, Student> function4 = Student::new; //使用构造器引用
System.out.println(function3.apply("Moti",20));
System.out.println(function4.apply("Moti",20));
}
@Test
public void Test1() {
Supplier<Student> supplier = () -> new Student(); //使用Lambda表达式
Supplier<Student> supplier1 = Student::new; //使用构造器引用
}
以上方法中function1和function2对应的构造器是
public Student(String name) {
this.name = name;
}
而function3和function4对应的构造器是
public Student(String name, int age) {
this.name = name;
this.age = age;
}