Function 是什么
相当于一个黑箱,放在哪儿,规定了,放入箱子的东西和箱子输出的东西是什么,当你有一个业务中,前后逻辑固定,但是中间的某些操作不固定的时候,可以用。
其实
List<String> test1 = Arrays.asList("325134514365437", "797683512413241253");
List<Integer> test2= test1.stream().map(Integer::valueOf).collect(Collectors.toList());
也是可以写成
List<String> test1 = Arrays.asList("325134514365437", "797683512413241253");
Function<String,Integer> test3 = p->Integer.valueOf(p);
List<Integer> test2= test1.stream().map(test3).collect(Collectors.toList());
在这里的逻辑就是,获取test2的一个数据->被map处理->下一个数据->被map处理
而这里map中的处理就可以根据自己的需求调整。
差不多就这么个事儿。

Function 使用场景
最简单的,最常见的,List.stream的流处理(如上),比如类型转换,或者数据处理。
以下距离并用代码说明一个案例
比如当前有一个业务逻辑,有实体类,ABCD。
规定当我们想要获取ABCD内的内容的时候,需要获取对应类的token来验证后,才能获取和返回对应的东西。(A.getToken1,A.getToken2,A.getToken3,A.getToken4)
这时候,我的流程就是

先定义结果要用的实体类
@Data
class a{
private String data;
private String id;
private String token;
}
@Data
class b{
private String price;
private String sales;
private String token;
}
然后定义Function逻辑
public static <T, R> R fetchAndLog(T entity,//需要被处理的实体类
Function<T, String> getT, // 不确定的Token获取方法,这里规定了Token只能是String,也就是getT操作返回的只能是string 的
Function<T, R> getP // 不确定的内容获取方法
) {
String T = getT.apply(entity);//这里entity对应 Function<T, String>的T,也就是输入的类。
//然后就是多token的验证,但是这里简化一下,只要全是数字就给过
if(!T.matches("^\\d+$")){
throw new IllegalStateException("token错误,请检查");
}else {
//把实体类作为参数塞入Function,执行不确定的获取方法
return getP.apply(entity);
}
}
最后使用它们
public static void main(String[] args) {
a aTest = new a();
b bTest = new b();
//aTest和bTest中间参数加载过程省略
System.out.println(fetchAndLog(aTest,a::getToken,a::getData));
//或者写成
Function<a,String> at = a-> a.getToken();
Function<a,String> ad = a-> a.getData();
System.out.println(fetchAndLog(aTest,at,ad));
//b类的
System.out.println(fetchAndLog(bTest,b::getToken,b::getPrice));
//或者写成
Function<b,String> bt = b-> b.getToken();
Function<b,String> bd = b-> b.getPrice();
System.out.println(fetchAndLog(bTest,bt,bd));
}
如果不使用Function,那就需要写成
//添加方法
private static boolean token(String s){ if(!s.matches("^\\d+$")){ throw new IllegalStateException("token错误,请检查"); }else { //把实体类作为参数塞入Function,执行不确定的获取方法 return true; } }
然后直接写逻辑
public static void main(String[] args) { a aTest = new a(); b bTest = new b(); //aTest和bTest中间参数加载过程省略 if (token(aTest.getToken())) { System.out.println(aTest.getData()); } if (token(bTest.getToken())) { System.out.println(bTest.getPrice()); } }
每次你都需要再写一个if (token(bTest.getToken()))但是如果使用了Function就可以省略这一步。