这几个接口经常与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)
示例
- Supplier
private staticT testSupplier(Supplier supplier) { return supplier.get(); } ... Integer s = testSupplier(() -> 7 + 3); // 不接受任何参数,但会返回数据 System.out.println(s); // 输出10
- Consumer
private staticvoid testConsumer(Consumer consumer, T data) { consumer.accept(data); } ... testConsumer(System.out::println, "dummy"); // 直接调用println,输出"dummy",无任何返回
- Runnable
private static void testRunnable(Runnable runnable) { runnable.run(); } ... testRunnable(() -> System.out.println("dummy")); // 既无输入,也无输出
- Function
private staticR testFunction(Function function, T data) { return function.apply(data); } ... Integer f = testFunction((d) -> d * 2, 3); // 既有输入,也有输出(将给定值X2) System.out.println(f); // 输出6
- Predicate
private staticboolean testPredicate(Predicate predicate, T data) { return predicate.test(data); } ... boolean p = testPredicate((d) -> d > 0, 100); // 接受输入,输出布尔值(判断给定值是否为正数) System.out.println(p); // 输出true
- @FunctionalInterface
@FunctionalInterface public interface CalculationFuncInterface{ public R apply(T l, U i); } ... private static R testFunctionalInterface(CalculationFuncInterface cal, T data1, U data2) { return cal.apply(data1, data2); } ... Integer fi = testFunctionalInterface((a, b) -> a * b, 6, 7); // 接受两个输入参数,并返回其乘积 System.out.println(fi); // 输出42
今天的介绍就先到这,感谢大家,Cheers!
公众号“程序员杂书馆”,欢迎关注。 免费送出O'Reilly 纸质书(亦有一批PDF分享)!
![10907-20181212194313278-332975465.jpg](https://img2018.cnblogs.com/blog/10907/201812/10907-20181212194313278-332975465.jpg)
![10907-20181212194336663-1259197127.jpg](https://img2018.cnblogs.com/blog/10907/201812/10907-20181212194336663-1259197127.jpg)