JavaFunction的使用

一、基础概念与核心方法

​定义与作用​

Function<T, R> 是一个函数式接口,接收类型为 T 的输入参数,返回类型为 R 的结果。其核心方法为 apply(T t)。例如,将字符串转换为整数长度:

java

Function<String, Integer> lengthFunction = s -> s.length();

System.out.println(lengthFunction.apply("Java")); // 输出:4

​链式组合方法​

​andThen() :先执行当前函数,再将结果传递给后续函数。

​compose() :先执行参数中的函数,再将结果传递给当前函数。

示例:数学运算组合:

java

Function<Integer, Integer> multiplyByTwo = x -> x * 2;

Function<Integer, Integer> addThree = x -> x + 3;

// 先乘2再加3

Function<Integer, Integer> combined1 = multiplyByTwo.andThen(addThree);

// 先加3再乘2

Function<Integer, Integer> combined2 = addThree.compose(multiplyByTwo);

System.out.println(combined1.apply(5)); // 输出:13

System.out.println(combined2.apply(5)); // 输出:16

​异常处理​

使用 orElseThrow() 处理可能的空值或异常情况:

java

Function<String, Integer> parseFunction = s -> Integer.parseInt(s);

String input = "123";

int result = parseFunction.apply(input).orElseThrow(() -> new IllegalArgumentException("无效输入"));

二、实际应用场景

​数据转换​

在集合操作中,Function 可与 Stream API 结合,简化数据转换逻辑。例如,将字符串列表转为整数列表:

java

List numbers = Arrays.asList("1", "2", "3");

List intList = numbers.stream()

.map(Integer::parseInt)

.collect(Collectors.toList());

​业务逻辑封装​

替代冗长的条件分支,例如根据商品类型计算折扣价:

java

Function<Product, BigDecimal> discountFunction = product -> {

switch (product.getType()) {

case "A": return product.getPrice().multiply(new BigDecimal("0.9"));

case "B": return product.getPrice().multiply(new BigDecimal("0.8"));

default: return product.getPrice();

}

};

BigDecimal finalPrice = discountFunction.apply(product);

​动态组合操作​

在数据处理流水线中,灵活组合多个函数:

java

Function<String, String> trim = String::trim;

Function<String, String> toUpper = String::toUpperCase;

Function<String, String> addPrefix = s -> "Result: " + s;

String output = trim.andThen(toUpper).andThen(addPrefix).apply(" hello ");

System.out.println(output); // 输出:Result: HELLO

三、与 JDK 新特性的结合

​模式匹配(Java 17+)​​

在 switch 表达式中结合 Function,简化类型判断逻辑:

java

Function<Object, String> formatter = obj -> switch (obj) {

case Integer i -> "Integer: " + i;

case String s -> "String: " + s;

default -> "Unknown";

};

System.out.println(formatter.apply(10)); // 输出:Integer: 10

​记录类(Record)​​

通过 Function 转换记录类对象,例如提取字段:

java

record Person(String name, int age) {}

Function<Person, String> getName = Person::name;

System.out.println(getName.apply(new Person("Alice", 30))); // 输出:Alice

四、最佳实践建议

​避免过度嵌套:链式调用过长时,可拆分为多个中间函数。

​优先使用方法引用:如 String::length 替代 s -> s.length(),提升可读性。

​结合 Optional:处理可能为空的输入,例如 Function.andThen(Optional::ofNullable)。

通过上述方法,Function 能有效减少冗余代码(如消除 80% 的 if-else 分支),提升代码的模块化和可维护性。实践中可根据具体场景选择组合方式,并探索与 Lambda、Stream 等特性的深度结合。

相关推荐
CoderYanger2 小时前
Java EE 进阶:13. Spring事务和事务传播机制(第二弹)
java·开发语言·数据库·spring boot·后端·spring·java-ee
会编程的吕洞宾5 小时前
Spring AI 2.0 MCP 客户端实战:让 Java AI 应用接入现成工具
java·人工智能·经验分享·后端·spring
星恒随风7 小时前
从0实现C++ AI大模型接入SDK(八):SessionManager会话管理——智能指针、原子操作、线程安全与懒加载机制
linux·服务器·开发语言·c++·人工智能
yingjie1108 小时前
快榜GEO|官网 AI 可读性自查 12 项(附 Python 检测脚本)
开发语言·人工智能·python
Felven8 小时前
C. Make Them Equal
c语言·开发语言·前端
tryCbest8 小时前
Python 爬虫扩展篇(二):验证码的检测与人工介入——把“拦路虎”当作信号,而不是要征服的对手
开发语言·爬虫·python
Rain的Java大神之路9 小时前
10万QPS订单系统:缓存、ES、MQ三道连环题,我把踩过的坑一次讲透
java·后端·面试
Rain的Java大神之路9 小时前
LeetCode 45 跳跃游戏 II:大厂面试官最爱追问的贪心题,我把骨头给你拆干净了
java·后端·leetcode
风落青芜10 小时前
排序算法(四):归并排序、计数排序与算法总结
c语言·开发语言·数据结构·算法·排序算法