目录
一、方法引用
1.使用情景:
当要传递给Lambda体的操作,已经有实现的方法了,就可以使用方法引用
2.本质:
本质上就是Lambda表达式,也是函数式接口的实例
3.使用格式
对象::非静态方法
类::静态方法
类::非静态方法
4.使用要求
要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的形参列表和返回值烈性相同(只针对情况1和2)
package Functioninterface;
import org.junit.Test;
import java.util.Comparator;
import java.util.function.Consumer;
//方法引用的使用
/*1.使用情景:当要传递给Lambda体的操作,已经有实现的方法了,就可以使用方法引用。
2.方法引用:本质上就是Lambda表达式,也是函数式接口的实例
3.使用格式:三种情况:
对象::非静态方法
类::静态方法
类::非静态方法
4.使用要求:要求接口中的抽象方法的形参列表和返回值类型与方法引用的方法的形参列表和返回值烈性相同(只针对情况1和2)*/
public class demo2 {
/* 情况一:
Consumer中的void accept(T t);
PrintStream中的 void println(T t);*/
@Test
public void test01(){
Consumer<String>con1=str-> System.out.println(str);
con1.accept("成都");
System.out.println("“***************************");
Consumer<String>con2=System.out::println;
con2.accept("昆明");
}
/* 情况三:
compare中的int compare(T t1,T t2);
String中的 int t1.compareto(t2);
上述方法,虽然不满足使用要求,但可以运行,是因为其相当于将上面的t1来当做方法的调用者*/
@Test
public void test02(){
Comparator<String> com=(s1,s2)->s1.compareTo(s2);
System.out.println(com.compare("acd","ace"));
System.out.println("********************");
Comparator<String>com2=String::compareTo;
System.out.println(com2.compare("adc","aec"));
}
}
二、构造器引用和数组引用
1.构造器引用
和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。 抽象方法的返回值类型即为构造器所属的类的类型
2.数组引用
即将数组看成一个类,则写法和构造器引用一样
person类定义:
package Functioninterface;
public class Person {
private String name;
private int age;
public Person(){}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package Functioninterface;
import org.junit.Test;
import java.util.Arrays;
import java.util.function.BiFunction;
import java.util.function.Function;
/*一、构造器引用
和方法引用类似,函数式接口的抽象方法的形参列表和构造器的形参列表一致。
抽象方法的返回值类型即为构造器所属的类的类型*/
public class demo3 {
//BiFunction中的 R apply(T t,U u)
@Test
public void test01(){
BiFunction<String,Integer,Person>func=new BiFunction<String, Integer, Person>() {
@Override
public Person apply(String s, Integer integer) {
return new Person(s,integer);
}
};
System.out.println(func.apply("王铖",23));
System.out.println("*********************************************");
BiFunction<String,Integer,Person>func2=(name,age)->new Person(name,age);
System.out.println(func2.apply("蒲汶文",22));
System.out.println("_____________________________________________");
BiFunction<String,Integer,Person>func3=Person::new;
System.out.println(func3.apply("王铖",23));
System.out.println(func3.apply("蒲汶文",22));
}
/* 二、数组引用
即将数组看成一个类,则写法和构造器引用一样*/
@Test
public void test02(){
Function<Integer,String []>func=(length)->new String[length];
System.out.println(Arrays.toString(func.apply(10)));
System.out.println("_____________________________________");
Function<Integer,String []>func2=String []::new;
System.out.println(Arrays.toString(func2.apply(10)));
}
}