1、消费型接口
Conusmer<T>: 消费型接口----对象类型为T的对象应用操作,包含方法:
void accept(T t);
@Test
public void test13(){
ConsumerInter("我是消费性接口",(t)-> System.out.println(t));
}
public void ConsumerInter(String str,Consumer<String> con){
con.accept(str);
}
2、供给型接口
Supplier<T> :供给型接口----返回类型为T的对象,包含方法:
T get();
@Test
public void test14(){
List<Integer> list = SupplierInter(10, () -> (int) (Math.random() * 100));
for(Integer result : list){
System.out.println(result);
}
}
public List<Integer> SupplierInter(int num, Supplier<Integer> sup){
List<Integer> list = new ArrayList<>();
for(int i = 0; i < num; i++){
Integer result = sup.get();
list.add(result);
}
return list;
}
3、函数式接口
Function<t,R>:函数式接口---对象类型为T的对象应用操作,并返回结果,结果是R类型的对象。
R apply(T t);
@Test
public void test15(){
Employees employees = new Employees();
employees.setName("我是函数式接口");
employees.setAge(24);
employees.setSalary(9999.99);
String result = FunctionInter(employees, (e) -> e.getName());
System.out.println(result);
}
public String FunctionInter(Employees employees, Function<Employees,String> fun){
return fun.apply(employees);
}
4、函数式接口
Predicate<T> 断言式接口---确定类型为T的对象是否满足约束,并返回boolean值
boolean test(T t);
@Test
public void test16(){
List<Integer> list = new ArrayList<>();
list.add(23);
list.add(21);
list.add(25);
list.add(20);
List<Integer> integerList = PredictInter(list, (pre) -> pre > 24);
for(Integer i : integerList){
System.out.println(i);
}
}
public List<Integer> PredictInter(List<Integer> list, Predicate<Integer> pre){
List<Integer> arrayList = new ArrayList<>();
for(Integer in : list){
if(pre.test(in)){
arrayList.add(in);
}
}
return arrayList;
}
5、其它函数接口
函数试接口 | 参数类型 | 返回类型 | 用途 |
---|---|---|---|
BiFunction<T,R,U> | T,U | R | 对类型为T,U参数应用操作,返回R类型的结果,方法为R apply(T t,U u) |
UnaryOperator(Function子接口) | T | T | 对类型 为T的对象进行一元运算,并返回T类型的结果,方法为:T apply(T t) |
BinaryOperator(BiFunction 子接口) | T,T | T | 对类型为T的对象进行二元运算,并返回T类型的结果。包含方法为:T apply(T t1,T t2) |
BiConsumer<T,U> | T,U | void | 对类型为T,U参数引用操作,包含方法为:void accept(T t,U u) |
… | … | … | … |
其中根据自己的需要选取合适的函数接口,其中前4个为JDK8的4大核心函数式接口,理解前4个其余函数式接口自热而然都懂了