1. 方法引用: 若 Lambda 体中的内容有方法已经实现了,我们可以用 “方法引用” (可以理解为方法引用是 Lambda 表达式的另一种表现方式)
主要有三种语法格式:
- 对象 :: 实例方法名
- 类 :: 静态方法名
- 类 :: 实例方法名
注:
①: Lambda 体中调用方法的参数列表与返回值类型,函数式接口中抽象方法的函数列表和返回值类型保持一致!
②: 若 Lambda 参数类表中的第一个参数(x)是 实例方法的调用着(x.equals(y)),而第二个参数是实例方法的参数时,可以使用 ClassName::method
这是所有导包
import lambda.Person;
import org.junit.Test;
import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.*;
对象::实例方法名
@Test
public void test1(){
//消费型接口(有参数无返回)
Consumer<String> con = x -> System.out.println(x); //实例方法
PrintStream ps = System.out;
Consumer<String> con1 = ps::println; //返回值相同 void
con1.accept("对象::实例方法名");
Consumer<String> con2 = System.out::println; //返回值相同 void
con1.accept("对象::实例方法名111111");
}
结果:
对象::实例方法名
对象::实例方法名111111
@Test
public void test2(){
Person ps = new Person();
//供给型接口 (没有参数,有返回值)
Supplier<String> supplier = () -> ps.getName();
String str = supplier.get();
System.out.println(str);
Supplier<Integer> supplier1 = ps::getAge;
Integer integer = supplier1.get();
System.out.println(integer);
}
结果:
null
0
类::静态方法名
@Test
public void test3(){
Comparator<Integer> comparator = (x,y) -> Integer.compare(x,y);
comparator.compare(1,2);
Comparator<Integer> comparator1 = Integer::compare;
comparator1.compare(1,2);
}
类::实例方法名
@Test
public void test4(){
BiPredicate<String,String> bp = (x,y) -> x.equals(y);
boolean test = bp.test("1", "2");
System.out.println(test);
BiPredicate<String,String> bp1 = String::equals;
boolean test1 = bp1.test("2","2");
System.out.println(test1);
}
结果:
false
true
二, 构造器引用:
- 格式:
ClassName::new - 注意:
需要调用的构造器参数列表要与函数式接口中的抽象方法的参数列表保持一致
构造器引用 无参
@Test
public void test5(){
Supplier<Person> sup = () -> new Person();
Person person1 = sup.get();
System.out.println(person1);
Supplier<Person> sup1 = Person::new;
Person person = sup1.get();
System.out.println(person);
}
结果:
Person{id=0, name='null', age=0, salary=0.0}
Person{id=0, name='null', age=0, salary=0.0}
构造器引用 有参:
创建类Person:
@Getter
@Setter
@ToSting
public class Person {
private int id;
private String name;
private int age;
private double salary;
public Person(){
}
public Person(int id) {
this.id = id;
}
public Person(int id, int age) {
this.id = id;
this.age = age;
}
}
注解无法使用手动添加get,set,toString方法
编写测试:
@Test
public void test6(){
Function<Integer,Person> fun = (x) -> new Person(x);
Function<Integer,Person> fun1 = Person::new;
Person apply = fun1.apply(1);
System.out.println(apply);
BiFunction<Integer,Integer,Person> biFunction = Person::new;
Person apply1 = biFunction.apply(1, 2);
System.out.println(apply1);
}
结果:
Person{id=1, name='null', age=0, salary=0.0}
Person{id=1, name='null', age=2, salary=0.0}
调用方法时,将会自动匹配参数类型和参数个数
三, 数组引用:
Type::new
@Test
public void test7(){
Function<Integer,String[]> fun = x -> new String[x];
String[] strs = fun.apply(10);
System.out.println(strs.length);
Function<Integer,Integer[]> function = Integer[]::new;
Integer[] ints = function.apply(9);
System.out.println(ints.length);
}
结果:
10
9
- 不完善,自己都还没太懂,后续会补上