文章目录
1、方法引用
- 1、方法引用
- 2、构造器引用
- 3、数组引用
方法引用本质上就是Lambda表达式. Lambda表达式作为函数式接口的实例,所以方法引用,也是函数式接口的实例。 使用格式:
类(或对象) :: 方法名
方法引用具体分为:
- 对象 :: 非静态方法 要求:接口中的抽象方法的形参列表和返回值类型与方法引用的方法的形参列表和返回值类型相同
public static void main(String[] args) { Dept dept = new Dept(30, "SALES", "CHICAGO"); Supplier sup1 = () -> dept.getDname(); System.out.println(sup1.get()); Supplier sup2 = dept::getDname; // Supplier中的T get() System.out.println(sup2.get()); Consumer con1 = str->System.out.println(str); con1.accept("haha"); Consumer con2 = System.out::println;//Consumer中的void accept(T t) con2.accept("haha"); }
- 类 :: 静态方法 要求:接口中的抽象方法的形参列表和返回值类型与方法引用的方法的形参列表和返回值类型相同
public static void main(String[] args) { //Comparator中的int compare(T t1,T t2) //Integer中的int compare(T t1,T t2) Comparator com1 = (item1, item2) -> Integer.compare(item1,item2); System.out.println(com1.compare(2,7)); Comparator com2 = Integer::compare; System.out.println(com2.compare(2,7)); //Function中的R apply(T t) //Math中的Long round(Double d) Function func1 = d -> Math.round(d); System.out.println(func1.apply(12.3)); Function func2 = Math::round; System.out.println(func2.apply(12.6)); }
- 类 :: 非静态方法
public static void main(String[] args) {
Dept dept = new Dept();
BiConsumer bc = Dept::setDname;
bc.accept(dept, "sales");
System.out.println(dept);//Dept{deptno=null, dname='sales', loc='null'}
Comparator com = String::compareTo;
System.out.println(com.compare("zhangsan", "lisi"));//14
BiPredicate pre2 = String::equals;
System.out.println(pre2.test("zhangsan", "lisi"));//false
}
2、构造器引用
要求,函数式接口的抽象方法的形参列表和构造器的形参列表一致。 抽象方法的返回值类型即为构造器所属的类的类型 示例:
public static void main(String[] args) {
//Supplier中的T get()
Supplier sup1 = () -> new Dept();
System.out.println(sup1.get());
Supplier sup2 = Dept::new;
System.out.println(sup2.get());
System.out.println(new Random(23).nextInt());
Function fun = Random::new;
Random random = fun.apply(23);
System.out.println(random.nextInt());
}
3、数组引用
把数组看做是一个特殊的类,则写法与构造器引用一致。
public static void main(String[] args) {
Function func1 = len -> new String[len];
String[] arr1 = func1.apply(5);
System.out.println(Arrays.toString(arr1));
Function func2 = String[] :: new;
String[] arr2 = func2.apply(5);
System.out.println(Arrays.toString(arr2));
Function func3 = ArrayList:: new;
ArrayList list = func3.apply(5);
list.add("1");
list.add("2");
list.add("3");
System.out.println(list);
}