博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java Lambda基础——Function, Consumer, Predicate, Supplier, 及FunctionalInterface接口
阅读量:7028 次
发布时间:2019-06-28

本文共 2114 字,大约阅读时间需要 7 分钟。

这几个接口经常与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 testSupplier(Supplier
 supplier) {
    return supplier.get(); } ... Integer s = testSupplier(() -> 7 + 3); // 不接受任何参数,但会返回数据 System.out.println(s); // 输出10
  1. Consumer
private static 
 void testConsumer(Consumer
 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 
 R testFunction(Function
 function, T data) {
    return function.apply(data); } ... Integer f = testFunction((d) -> d * 2, 3); // 既有输入,也有输出(将给定值X2) System.out.println(f); // 输出6
  1. Predicate
private static 
 boolean testPredicate(Predicate
 predicate, T data) {
    return predicate.test(data); } ... boolean p = testPredicate((d) -> d > 0, 100); // 接受输入,输出布尔值(判断给定值是否为正数) System.out.println(p); // 输出true
  1. @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
10907-20181212194336663-1259197127.jpg

转载地址:http://uloxl.baihongyu.com/

你可能感兴趣的文章
IOS开发--循环引用问题,普通控件为什么用weak,代理为什么用weak,block内用到外面的东...
查看>>
Java初学者怎么学习才能快速入门?
查看>>
AJPFX对选择和冒泡两种排序的理解
查看>>
磁盘管理之MBR
查看>>
Linux系统管理(一)
查看>>
鼠标悬停整行变色
查看>>
我的友情链接
查看>>
活动目录数据库
查看>>
java中标签的作用
查看>>
安装maven及eclipse中安装maven插件
查看>>
Eclipse去除js(JavaScript)文件上的小红叉
查看>>
AngularJS—— 指令的交互
查看>>
Nginx + tomcat + Memcached(session共享)
查看>>
运维的我要学开发--Flask(1)
查看>>
flash播放代码
查看>>
ArrayList新new法,以前没这么写过
查看>>
postfix邮箱服务器安装和配置
查看>>
我的友情链接
查看>>
boost_tutorial
查看>>
Android多媒体学习
查看>>