3-方法引用与构造器引用 方法引用
当要传递给Lambda体的操作,已经有实现的方法了,可以使用方法引用! (实现抽象方法的参数列表,必须与方法引用方法的参数列表保持一致!) 方法引用:使用操作符 “::” 将方法名和对象或类的名字分隔开来。 如下三种主要使用情况:
对象::实例方法 类::静态方法 类::实例方法
注意:当需要引用方法的第一个参数是调用对象,并且第二个参数是需要引用方法的第二个参数(或无参数)时:ClassName::methodName
构造器引用
格式: ClassName::new 与函数式接口相结合,自动与函数式接口中方法兼容。 可以把构造器引用赋值给定义的方法,与构造器参数列表要与接口中抽象方法的参数列表一致!
数组引用
格式: type[] :: new
package day01.com.lm.java8;
import org.junit.Test;
import java.io.PrintStream;
import java.util.Comparator;
import java.util.function.*;
public class TestMethodRef {
@Test
public void test1() {
String abcdef = "abcdef";
PrintStream ps1 = System.out;
Consumer<String> con = (x) -> ps1.println(x);
con.accept(abcdef);
PrintStream ps = System.out;
Consumer<String> con1 = ps::println;
con1.accept(abcdef);
Consumer<String> con2 = System.out::println;
con2.accept(abcdef);
}
@Test
public void test2() {
Employee emp = new Employee();
Supplier<String> sup = () -> emp.getName();
String str = sup.get();
System.out.println(str);
Supplier<Integer> sup2 = emp::getAge;
Integer num = sup2.get();
System.out.println(num);
}
@Test
public void test3() {
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
System.out.println(com.compare(6, 7));
Comparator<Integer> com1 = Integer::compare;
System.out.println(com1.compare(6, 7));
}
@Test
public void test4() {
BiPredicate<String, String> bp = (x, y) -> x.equals(y);
System.out.println(bp.test("abc", "abc"));
BiPredicate<String, String> bp2 = String::equals;
System.out.println(bp2.test("abc", "abc"));
System.out.println(bp2.test("abc", null));
}
@Test
public void test5() {
Supplier<Employee> sup = () -> new Employee();
Supplier<Employee> sup2 = Employee::new;
Employee emp = sup2.get();
System.out.println(emp);
}
@Test
public void test6() {
Function<Integer, Employee> fun = (x) -> new Employee(x);
Function<Integer, Employee> fun2 = Employee::new;
Employee emp = fun2.apply(101);
System.out.println(emp);
}
@Test
public void test7() {
Function<Integer, String[]> fun = (x) -> new String[x];
String[] strs = fun.apply(10);
System.out.println(strs.length);
Function<Integer, String[]> fun2 = String[]::new;
String[] strs2 = fun2.apply(20);
System.out.println(strs2.length);
}
}
|