Funtion介绍
函数式接口就是(Functional Interface )指的是有且只有一个抽象方法,但可以有多个非抽象方法的接口。
我知道这么说比较笼统,但如果想要深刻理解这个是什么意思,光靠字面说说是远远不够的,此次就以近期接触的项目作为入口,我们谈谈它的好用之处在哪
需求
可以用对象的方法,去绑定一个方法作为入参,实现一些通过功能,话不多说,贴代码。StudentDataModel.java,使用Function作为入参,调用apply获得绑定对象的方法执行之后的值
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public class StudentDataModel<T> {
private LinkedHashMap<String,Function> maps = new LinkedHashMap<>();
private List<T> allObjs ;
public <V>StudentDataModel addValue(String valueKey , Function<T,V> functionTest ){
maps.put(valueKey,functionTest);
return this;
}
public void setData( List<T> Items){
allObjs = Items;
}
public void show(){
for(T item : allObjs){
for(Map.Entry<String,Function> entry : maps.entrySet()){
Function functionTest = entry.getValue();
System.out.print(functionTest.apply(item));
}
}
}
}
Model 测试类Student.java
public class Student {
private String name ;
private String code;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
import java.util.ArrayList;
import java.util.List;
public class TestMain {
public static void main(String args[]){
StudentDataModel<Student> studentStudentDataModel = new StudentDataModel<>();
studentStudentDataModel.addValue("1",Student::getName);
studentStudentDataModel.addValue("2",Student::getCode);
List<Student> studentList = new ArrayList<>();
Student studentTest1 = new Student();
studentTest1.setName("kimler");
studentTest1.setCode("001");
Student studentTest2 = new Student();
studentTest2.setName("jack");
studentTest2.setCode("002");
studentList.add(studentTest1);
studentList.add(studentTest2);
studentStudentDataModel.setData(studentList);
studentStudentDataModel.show();
}
}
以及最后的运行结果。
有了能把方法作为参数的用法,很多功能就可以写的很通用,我也在继续学习。。