基于Java8 函数式接口理解及测试
1.函数式接口的理解
根据重构的思想,需要把容易变化的模块进行抽象并封装起来,从这个点来看,Java8新引入的函数式接口就是基于这个思想进行设计的。
2.函数式接口定义
2.1自定义如下
需要FunctionalInterface关键字显示声明:
@FunctionalInterface
publicinterfaceAppleInterface{
publicvoidtest();
}
2.2系统预定义
java.util.function.Consumer; java.util.function.Function; java.util.function.Predicate; java.util.function.Supplier;
可以去查看源码了解具体的细节,这几个接口包括了常用的一些场景,一般可满足需要
3.函数式接口的使用
函数式接口一般使用前需要先定义,也可以使用系统预定义的几个函数式接口
函数式接口的使用和使用一个变量没有区别,显示声明定义,格式如下:
FunctionInterfaceinterface=null;
这里的interface虽然看起来是一个变量,可是实际却是一段行为代码,用于执行具体的业务逻辑,可以自由在方法接口间传递,也可以直接执行
interface.doSomeThing();
如定义函数式接口为参数的接口:
publicvoidfilter(FunctionInterfaceinterface)
{
interface.doSomeThing();
}
4.函数式接口练习
4.1自定义实体类Apple
publicclassApple{
privateStringcolor;
privatefloatweight;
publicApple(Stringcolor,floatweight){
this.color=color;
this.weight=weight;
}
publicStringgetColor(){
returncolor;
}
publicvoidsetColor(Stringcolor){
this.color=color;
}
publicfloatgetWeight(){
returnweight;
}
publicvoidsetWeight(floatweight){
this.weight=weight;
}
}
4.2自定义函数式接口
该接口有一个test方法,不接收任何参数,也没有任何返回
@FunctionalInterface
publicinterfaceAppleInterface{
publicvoidtest();
}
4.3测试自定义函数式接口
@Test
publicvoidDefineFunctionInterface(){
//自定义函数式接口
AppleInterfaceat=()->System.out.println("defineFunctionInterfaceAppleInterface.");
at.test();
}
至此,就完成一个很简单的函数式接口的定义和调用
4.4系统预定义函数式接口
Consumer
@Test
publicvoidConsumerTest(){
Consumerconsumer=(Appleapp)->{System.out.println(app.getColor()+","+app.getWeight());};
Listapps=Arrays.asList(newApple("red",120),newApple("blue",80),
newApple("green",100));
ConsumerApple(apps,consumer);
}
publicvoidConsumerApple(Listapps,Consumerc){
for(Appleapp:apps){
c.accept(app);
}
}
    
Supplier
@Test
publicvoidSupplierTest(){
Suppliersupplier=()->{returnnewApple("hellosupplier",999);};
Appleapp=supplier.get();
System.out.println(app.getColor()+","+app.getWeight());
} 
Predicate
@Test
publicvoidPredicateTest(){
//系统预定义函数式接口测试
Predicatep1=(Applea)->{if(a.getWeight()>90)returntrue;returnfalse;};
Predicatep2=(Applea)->{if(a.getColor().equals("blue"))returntrue;returnfalse;};
Listapps=Arrays.asList(newApple("red",120),newApple("blue",80),
newApple("green",100));
filterApple(apps,p1);//筛选重量大于90g的苹果
filterApple(apps,p2);//筛选蓝色的苹果
}
publicvoidfilterApple(Listapps,Predicatep){
for(Appleapp:apps){
if(p.test(app)){
System.out.println(app.getColor()+","+app.getWeight());
}
}
}
     
Function
@Test
publicvoidFunctionTest(){
Functionfunction=(Strings)->{returnnewApple(s,666);};
Appleapp=function.apply("red");
System.out.println(app.getColor()+","+app.getWeight());
app=function.apply("green");
System.out.println(app.getColor()+","+app.getWeight());
}
 
以上这篇基于Java8函数式接口理解及测试就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
