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 等特性的深度结合。

相关推荐
Yue丶越几秒前
【Python】基础语法入门(二)
android·开发语言·python
Demon--hx2 分钟前
[c++]string的三种遍历方式
开发语言·c++·算法
SteveCode13 分钟前
血赚不亏!Java 17 9 个炸裂特性,程序员看完直呼:太香了!
java
共享家952715 分钟前
QT-系统(多线程)
开发语言·数据库·qt
BLOB_10100127 分钟前
关于懒人复制idea项目的坑
java·ide·intellij-idea
Moe48830 分钟前
Spring Boot 自动配置核心:AutoConfigurationImportSelector 深度解析
java·后端·设计模式
郝学胜-神的一滴43 分钟前
Effective Python 第52条:用subprocess模块优雅管理子进程
linux·服务器·开发语言·python
valan liya1 小时前
C++list
开发语言·数据结构·c++·list
6***x5451 小时前
Java设计模式之策略模式
java·设计模式·策略模式
Le1Yu1 小时前
订单取消功能(退款功能、策略模式、定时任务)
开发语言