第二章 Lambda表达式

面向对象编程是对数据进行抽象,而函数式编程是对行为进行抽象。现实世界中,数据和行为并存

第二章 Lambda表达式

匿名内部类:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        System.out.println("button clicked");
    }
});

使用Lambdas,event的括号要不要都行。

button.addActionListener((event) -> System.out.println("button clicked"));

Lambda表达式其他变体:

Runnable noArguments = () -> System.out.println("Hello World");

Runnable multiStatement = () -> { 
            System.out.print("Hello");
            System.out.println(" World");
        };

ActionListener oneArgument = event -> System.out.println("button clicked");

BinaryOperator<Long> add = (x, y) -> x + y; 
BinaryOperator<Long> addExplicit = (Long x, Long y) -> x + y;

这些都是接口的实现。

什么是函数接口?

函数接口是只有一个抽象方法的接口,用作Lambda表达式的类型。

java中重要的函数接口

接口参数返回类型实例
PredicateTboolean这张唱片发行了没?
ConsumerTvoid利用输入参数,println输出一个值
FunctionTR获得一个Car对象的名字
SupplierNoneT工厂方法
UnaryOperatorTT逻辑非(!)
BinaryOperator(T,T)T求两个乘数的乘积

如,类型推断

Predicate<Integer> atLeast5 = x -> x > 5;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值