跳转到内容

Java Function接口

来自代码酷

模板:Note

Java Function接口[编辑 | 编辑源代码]

Function接口是Java 8引入的函数式接口,位于`java.util.function`包中。它代表一个接受单一输入参数并返回结果的函数。在Lambda表达式和方法引用中广泛使用,是函数式编程的核心组件之一。

基本定义[编辑 | 编辑源代码]

Function接口的泛型定义为:

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);
    // 其他默认方法...
}

其中:

  • T:输入参数类型
  • R:返回结果类型

核心方法[编辑 | 编辑源代码]

apply()[编辑 | 编辑源代码]

主要抽象方法,执行函数逻辑:

Function<String, Integer> lengthFunction = s -> s.length();
System.out.println(lengthFunction.apply("Hello")); // 输出:5

compose()[编辑 | 编辑源代码]

先执行参数中的函数,再执行当前函数:

Function<Integer, String> intToString = Object::toString;
Function<String, String> quote = s -> "'" + s + "'";

Function<Integer, String> quoteIntToString = quote.compose(intToString);
System.out.println(quoteIntToString.apply(123)); // 输出:'123'

andThen()[编辑 | 编辑源代码]

先执行当前函数,再执行参数中的函数:

Function<Integer, Integer> times2 = e -> e * 2;
Function<Integer, Integer> squared = e -> e * e;

Function<Integer, Integer> composed = times2.andThen(squared);
System.out.println(composed.apply(3)); // 输出:36 (3*2=6, 6²=36)

特殊变体[编辑 | 编辑源代码]

Function接口变体
接口 描述 示例
IntFunction<R> 接受int参数 IntFunction<String> f = i -> "Value: "+i;
DoubleFunction<R> 接受double参数 DoubleFunction<String> f = d -> "Value: "+d;
ToIntFunction<T> 返回int结果 ToIntFunction<String> f = String::length;
BiFunction<T,U,R> 接受两个参数 BiFunction<String,String,Integer> f = (s1,s2) -> s1.length()+s2.length();

实际应用案例[编辑 | 编辑源代码]

案例1:字符串处理流水线[编辑 | 编辑源代码]

Function<String, String> trim = String::trim;
Function<String, String> toUpper = String::toUpperCase;
Function<String, String> replaceVowels = s -> s.replaceAll("[aeiou]", "*");

Function<String, String> pipeline = trim.andThen(toUpper).andThen(replaceVowels);

System.out.println(pipeline.apply("  hello world  ")); 
// 输出:H*LL* W*RLD

案例2:数据转换器[编辑 | 编辑源代码]

flowchart LR A[原始数据] --> B(Function1: JSON解析) B --> C(Function2: 数据验证) C --> D(Function3: 转换为领域对象) D --> E[处理结果]

Function<String, Map<String,Object>> jsonParser = json -> { /* 解析逻辑 */ };
Function<Map<String,Object>, Boolean> validator = map -> { /* 验证逻辑 */ };
Function<Map<String,Object>, User> toUser = map -> new User(map);

Function<String, Optional<User>> conversionPipeline = jsonParser
    .andThen(validator)
    .andThen(toUser)
    .andThen(Optional::ofNullable);

数学表示[编辑 | 编辑源代码]

Function接口可以表示为数学函数: f:TR

函数组合表示为: (fg)(x)=f(g(x)) 对应代码中的`compose()`方法。

性能考虑[编辑 | 编辑源代码]

  • 简单Lambda表达式会被JIT内联优化
  • 复杂函数链可能产生临时对象
  • 对于原始类型,考虑使用`IntFunction`等变体避免装箱

最佳实践[编辑 | 编辑源代码]

1. 保持函数纯净(无副作用) 2. 适当分解复杂函数链 3. 为业务意义的Function声明具名变量 4. 优先使用方法引用提高可读性 5. 注意空值处理(可结合Optional使用)

页面模块:Message box/ambox.css没有内容。

进阶主题[编辑 | 编辑源代码]

柯里化(Currying)[编辑 | 编辑源代码]

将多参数函数转换为一系列单参数函数:

Function<Integer, Function<Integer, Integer>> adder = a -> b -> a + b;
Function<Integer, Integer> add5 = adder.apply(5);
System.out.println(add5.apply(3)); // 输出:8

函数组合[编辑 | 编辑源代码]

使用`compose()`和`andThen()`构建处理流水线:

flowchart LR A --> B --> C --> D

与Stream API结合[编辑 | 编辑源代码]

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<Integer> lengths = names.stream()
    .map(String::length)
    .collect(Collectors.toList());
// lengths = [5, 3, 7]

常见问题[编辑 | 编辑源代码]

模板:Q&A 模板:Q&A

总结[编辑 | 编辑源代码]

Function接口为Java带来了函数式编程能力,通过:

  • 将行为参数化
  • 支持函数组合
  • 与Lambda表达式完美配合

掌握Function接口可以显著提高代码的表达力和模块化程度。