Java Lambda基础——Function, Consumer, Predicate, Supplier, 及FunctionalInterface接口

这几个接口经常与Lambda结合使用,网上当然也有很多介绍,不过有些过于繁琐,有些又偏简单,秉着实用主义精神,今天这里折中一下,把介绍的内容分为两部分,第一部分相当于TLDR,总结几个“口诀”,便于大家记忆,对于更想看用法示例的同学们,第二部分者提供了所有这些接口的示例。希望对大家有所帮助。

口诀

    如无参数,请使用Supplier(Use Supplier if it takes nothing)

    如无返回,请使用Consumer(Use Consumer if it returns nothing)

    如两者都无,请使用Runnable(Use Runnable if it does neither)

    如两者都有,请使用Function(Use Function if it does both)

    如返回布尔值,请使用Predicate(Use Predicate if it returns a boolean)

    如以上皆不可以,请使用自定义@FunctionalInteface(Use @FunctionalInteface if none of above works)

示例

  1. Supplier
private static <T> T testSupplier(Supplier<T> supplier) {
    return supplier.get();
}
...
Integer s = testSupplier(() -> 7 + 3); // 不接受任何参数,但会返回数据
System.out.println(s); // 输出10
  1. Consumer
private static <T> void testConsumer(Consumer<T> consumer, T data) {
    consumer.accept(data);
}
...
testConsumer(System.out::println, "dummy"); // 直接调用println,输出"dummy",无任何返回
  1. Runnable
private static void testRunnable(Runnable runnable) {
    runnable.run();
}
...
testRunnable(() -> System.out.println("dummy")); // 既无输入,也无输出
  1. Function
private static <T, R> R testFunction(Function<T, R> function, T data) {
    return function.apply(data);
}
...
Integer f = testFunction((d) -> d * 23); // 既有输入,也有输出(将给定值X2)
System.out.println(f); // 输出6
  1. Predicate
private static <T> boolean testPredicate(Predicate<T> predicate, T data) {
    return predicate.test(data);
}
...
boolean p = testPredicate((d) -> d > 0100); // 接受输入,输出布尔值(判断给定值是否为正数)
System.out.println(p); // 输出true
  1. @FunctionalInterface
@FunctionalInterface
public interface CalculationFuncInterface<T, U, R> {
    public R apply(T l, U i);
}
...
private static <T, U, R> R testFunctionalInterface(CalculationFuncInterface<T, U, R> cal, T data1, U data2) {
    return cal.apply(data1, data2);
}
...
Integer fi = testFunctionalInterface((a, b) -> a * b, 67); // 接受两个输入参数,并返回其乘积
System.out.println(fi); // 输出42

今天的介绍就先到这,感谢大家,Cheers!



公众号“后厂村思维导图馆”,欢迎关注。免费送出O'Reilly《Spark快速大数据分析》纸质书(亦有一批PDF分享)!

posted @   后厂村思维导图馆  阅读(3018)  评论(2编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示