Function接口
java.util.function.Function 接口用来根据一个类型的数据得到另一个类型的数据,前者称为前置条件, 后者称为后置条件。
1、抽象方法:apply
Function 接口中最主要的抽象方法为: R apply(T t) ,根据类型T的参数获取类型R的结果。 使用的场景例如:将 String 类型转换为 Integer 类型。
public class Demo01Function {
/*
* 定义一个方法
* 方法的参数传递一个字符串类型的整数
* 方法的参数传递一个Function接口,泛型使用<String,Integer>
* 使用Function接口中的方法apply,把字符串类型的整数,转换为Integer类型的整数
* */
public static void change(String s, Function<String,Integer> fun){
//Integer in = fun.apply(s);
int in = fun.apply(s);//自动拆箱 Integer -> int
System.out.println(in);
}
public static void main(String[] args) {
//定义一个字符串类型的整数
String s = "1234";
//调用change方法,传递字符串类型的整数,和lambda表达式
change(s,(String str) -> {
//把字符串类型的整数,转换为Integer类型的整数返回
return Integer.parseInt(str);
});
}
}
2、默认方法:andThen
Function 接口中有一个默认的 andThen 方法,用来进行组合操作。JDK源代码如:
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) ‐> after.apply(apply(t));
}
该方法同样用于“先做什么,再做什么”的场景,和 Consumer 中的 andThen 差不多:
/*
* Function接口中的默认方法andThen:用来进行组合操作
*
* 需求:
* 把String类型的"123",转换为Integer类型,把转换后的结果加10
* 把增加之后的Integer类型的数据,转换为String类型
* 分析:
* 转换了两次
* 第一次是把String类型转换为了Integer类型
* 所以我们可以使用Function<String,Integer>fun1
* Integer i = fun1.apply("123")+10;
* 第二次是把Integer类型转换为String类型
* 所以我们可以使用Function<Integer,String>fun2
* String s = fun2.apply(i);
* 我们可以使用andThen方法,把两次转换组合在一起使用
* String s = fun1.andThen(fun2).apply("123");
* fun1先调用apply方法,把字符串转换为Integer
* fun2再调用apply方法,把Integer转换为字符串
* */
public class Demo02Function_andThen {
/*
* 定义一个方法
* 参数串一个字符串类型的整数
* 参数再传递两个Function接口
* 一个泛型使用Function<String,Integer>fun1
* 一个泛型使用Function<Integer,String>fun2
* */
public static void change(String s,Function<String,Integer> fun1, Function<Integer,String> fun2){
String ss = fun1.andThen(fun2).apply(s);
System.out.println(ss);
}
public static void main(String[] args) {
//定义一个字符串类型的整数
String s = "123";
//调用change方法,传递字符串和两个Lambda表达式
change(s,(String str) -> {
//把字符串转换为整数 + 10
return Integer.parseInt(str) + 10;
},(Integer i) -> {
//把整数转换为字符串
return i + "";
});
}
}
第一个操作是将字符串解析成为int数字并加上10,第二个操作是转为字符串。两个操作通过 andThen 按照前后顺序组合到了一 起。
请注意,Function的前置条件泛型和后置条件泛型可以相同。
练习:自定义函数模型拼接
题目
请使用 Function 进行函数模型的拼接,按照顺序需要执行的多个函数操作为:
String str = “赵丽颖,20”;
- 将字符串截取数字年龄部分,得到字符串;
- 将上一步的字符串转换成为int类型的数字;
- 将上一步的int数字累加100,得到结果int数字。
解答
import java.util.function.Function;
public class DemoFunction {
public static void main(String[] args) {
String str = "赵丽颖,20";
int age = getAgeNum(str, s ‐> s.split(",")[1],
s ‐>Integer.parseInt(s),
n ‐> n += 100);
System.out.println(age);
}
private static int getAgeNum(String str, Function<String, String> one,
Function<String, Integer> two,
Function<Integer, Integer> three) {
return one.andThen(two).andThen(three).apply(str);
}
}