java--函数式接口全面总结与使用场景指南
1. 无参无返回值 —
Runnable
接口方法:
void run()
用途:执行一段代码,无参数,无返回值。
Runnable task = () -> System.out.println("执行任务"); task.run();
2. 无参有返回值 —
Supplier<R>
接口方法:
R get()
用途:提供一个返回值,无参数。
Supplier<String> supplier = () -> "Hello World"; String s = supplier.get();
3. 有参无返回值 —
Consumer<T>
接口方法:
void accept(T t)
用途:接收一个参数,执行操作,无返回。
Consumer<String> consumer = msg -> System.out.println("消息:" + msg); consumer.accept("你好");
4. 有参有返回值 —
Function<T, R>
接口方法:
R apply(T t)
用途:接收一个参数,返回一个结果。
Function<String, Integer> func = s -> s.length(); int len = func.apply("Hello");
5. 两个参数无返回值 —
BiConsumer<T, U>
接口方法:
void accept(T t, U u)
用途:接收两个参数,执行操作,无返回值。
BiConsumer<String, Integer> biConsumer = (name, age) -> System.out.println(name + " 年龄是 " + age); biConsumer.accept("Tom", 20);
6. 两个参数有返回值 —
BiFunction<T, U, R>
接口方法:
R apply(T t, U u)
用途:接收两个参数,返回一个结果。
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b; int sum = add.apply(3, 5);
7. 多个参数有返回值 — 自定义接口
Java标准库不支持3个以上参数函数式接口,需要自定义
@FunctionalInterface public interface TriFunction<T, U, V, R> {R apply(T t, U u, V v); }
示例:
TriFunction<Integer, Integer, Integer, Integer> sumThree = (a, b, c) -> a + b + c; int result = sumThree.apply(1, 2, 3);
8. 多个参数无返回值 - 自定义 BiConsumer
@FunctionalInterface public interface TriConsumer<T, U, V> {void accept(T t, U u, V v); }TriConsumer<String, Integer, Boolean> printer = (name, age, isStudent) -> {System.out.println(name + " - " + age + " - 是学生: " + isStudent); };printer.accept("Alice", 22, true);
9. 总结表格
参数数量 返回类型 接口类型 方法名 示例 0 无 Runnable run() () -> {...} 0 有 Supplier get() () -> "Hello" 1 无 Consumer accept() x -> System.out.println(x) 1 有 Function<T,R> apply() s -> s.length() 2 无 BiConsumer<T,U> accept() (x,y) -> {...} 2 有 BiFunction<T,U,R> apply() (a,b) -> a + b 3+ 有 自定义 apply() (a,b,c) -> {...} 3+ 无 自定义 accept() (a,b,c) -> {...}
10. 使用场景举例
异步任务:用
Runnable
传递无参无返回的代码块。延迟计算:用
Supplier
提供值的生成。消费数据:用
Consumer
处理单个输入数据。转换数据:用
Function
做类型转换。带上下文操作:用
BiConsumer
处理两个参数操作。计算结果:用
BiFunction
计算两个输入的结果。复杂操作:用自定义接口支持多个参数。