1.方法引用
对象::方法 引用类型一样
public void test5(){
Consumer<String> con = System.out::println;
con.accept("消费一下");
Supplier<String> s1 = new Supplier<String>() {
@Override
public String get() {
return "得到";
}
};
Person person = new Person(12, "jack");
Supplier<String> s2 = ()->person.getName();
Supplier<String> s3 = person::getName;
System.out.println(s2.get());
System.out.println(s3.get());
}
对象::方法 引用类型不同,但是一个是调用者
public void test6(){
Comparator<Integer> com = (o1,o2)->Integer.compare(o1,o2);
System.out.println(com.compare(1, 2));
Comparator<Integer> com2 = Integer::compare;
System.out.println(com2.compare(1, 2));
Function<Double,Long> f1 = Math::round;
System.out.println(f1.apply(10.2));
System.out.println(f1.apply(10.6));
}
类::方法
public void test7(){
Comparator<String> com = (s1,s2)->s1.compareTo(s2);
System.out.println(com.compare("abc", "ab"));
Comparator<String> com2 = String::compareTo;
System.out.println(com2.compare("abc", "ab"));
Person person = new Person(12, "jack");
Function<Person,String > f1 = p->p.getName();
System.out.println(f1.apply(person));
Function<Person,String > f2 = Person::getName;
System.out.println(f2.apply(person));
}
2.构造函数引用
public void test8(){
Supplier<Person> s1 = ()->new Person();
System.out.println(s1.get());
Supplier<Person> s2 = Person::new;
System.out.println(s2.get());
Function<Integer,Person> f1 = t1->new Person(t1);
System.out.println(f1.apply(11));
Function<Integer,Person> f2 = Person::new;
System.out.println(f2.apply(12));
BiFunction<Integer,String,Person> f3 = Person::new;
System.out.println(f3.apply(11, "jack"));
}
3.数组引用
@Test
public void test9(){
Function<Integer,String[]> f1 = len->new String[len];
System.out.println(Arrays.toString(f1.apply(5)));
Function<Integer,String[]> f2 = String[]::new;
System.out.println(Arrays.toString(f2.apply(5)));
}