JDK8新特性 -- Function接口: apply,andThen,compose
1 Function<T, R>
中的T, R表示接口输入、输出的数据类型。
-
R apply(T t)
- apply:
-
.例子:
func
是定义好的Function
接口类型的变量,他的输入、输出都是Integer
类型,调用calculate
方法时,将func
作为参数传入,对参数5
进行处理。FunctionTest functionTest = new FunctionTest();
// return e + 5;就是apply方法的具体实现
Function<Integer, String> func = e -> {return String.valueOf(e + 6);};
String result = functionTest.calculate(5, func);
System.out.println(result);
public String calculate(Integer a, Function<Integer, String> function) {
return function.apply(a);
} -
andThen:
- 先处理参数,再对返回值使用
操作after
进行处理。
Function<Integer, Integer> func = e -> {return e + 5;};
Function<Integer, Integer> func2 = e -> {return e * 5;};
//func2即after
func.andThen(func2).apply(5); // 50
compose:
- 和
andThen
刚好相反:先使用操作before
处理参数,再对返回值进行处理。
Function<Integer, Integer> func = e -> {return e + 5;};
Function<Integer, Integer> func2 = e -> {return e * 5;};
//func2即before
func.compose(func2).apply(5); // 30 -
compose
源码:
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));//第一个apply是调用当前接口的方法
} - 注意
compose
方法的返回值依然是Function<T, R>
类型,所以不是
return this.apply(before.apply(v));
案例: - 先处理参数,再对返回值使用
-
public class FunctionTest2 { public static void main(String[] args) { FunctionTest2 functionTest2 = new FunctionTest2(); int result1 = functionTest2.compute(5, e -> e * 5, e -> e + 5); int result2 = functionTest2.compute2(5, e -> e * 5, e -> e + 5); int result3 = functionTest2.compute3(5, e -> e * 5, e -> e + 5); int result4 = functionTest2.compute4(5, e -> e * 5, e -> e + 5); System.out.println(result1);//50 System.out.println(result2);//30 System.out.println(result3);//130 System.out.println(result4);//250 }
public int compute(int source, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.compose(function2).apply(source);
}
public int compute2(int source, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.andThen(function2).apply(source);
}
public int compute3(int source, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.andThen(function2).compose(function1).apply(source); //从后往前 25 125 130
}
public int compute4(int source, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.compose(function2).andThen(function1).apply(source); } //10*5 50*5
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器