function(T,R)
- R apply(T t) 根据类型T的参数获取类型R的结果
- 使用场景例如,将String类型转化为Integer类型
public class Demo1Apply {
public static Integer change(String s,Function<String, Integer> fun){
return fun.apply(s);
}
public static void main(String[] args) {
int a = change("123",(s)->Integer.parseInt(s));
System.out.println(a);
}
}
- andThen()用来进行组合操作
public class Demo2AndTen {
//先把String转化为Integer,再把Integer转化为String
public static String change(String s, Function<String, Integer> fun1,Function<Integer,String> fun2){
return fun1.andThen(fun2).apply(s);
}
public static void main(String[] args) {
String str = change("78",(s)->Integer.parseInt(s)+10,(number)->number.toString());
System.out.println(str); //88
}
}
- Practise
public class Practise {
/*
* 1.将字符串截取到年龄部分,得到字符串
* 2.将上一步的字符串转化为int类型
* 3.将上一步的数字累加100
* */
public static int change(String s, Function<String, String> fun1,Function<String,Integer> fun2,Function<Integer, Integer> fun3){
return fun1.andThen(fun2).andThen(fun3).apply(s);
}
public static void main(String[] args) {
int number = change("你好,20",s->s.split(",")[1],s->Integer.parseInt(s),num->{
for (int i = 1; i <=100 ; i++) {
num+=i;
}
return num;
});
System.out.println(number);//5070
}
}
标签:Function,String,接口,static,Integer,public,change
From: https://www.cnblogs.com/-xyk/p/16794477.html