lambda表达式基本语法

1 、无参数,无返回值

() -> System.out.println("hello World")

Runnable hello_world = () -> System.out.println("hello World");

hello_world.run(); //控制台输出hello World

2 、有参数,无返回值

(x) -> System.out.println("hello "+x)

// 一个参数,无返回值

//(x) -> System.out.println("hello "+x)

//如果只有一个参数,括号可省略,如: x -> System.out.println("hello "+x)

Consumer hello_world1 = (x) -> System.out.println("hello "+x);

hello_world1.accept("PangHao");

 

3 、多个参数,有返回值

(x,y)->x+y

//多个参数有返回值,附带代码块

//(x,y)->x+y

IntBinaryOperator sumInt = (x, y) -> {

System.out.println(x + "+" + y + "=" + (x + y));

return x + y;

};

 

//如果单行语句不用写return和大括号

IntBinaryOperator tComparator = (x, y) -> x + y;

System.out.println(tComparator.applyAsInt(7,8));

 

4 、数据类型省略

/*

* Lambda 表达式中的参数类型都是由编译器推断得出的。

* Lambda 表达式中无需指定类型,程序依然可以编译,这是因为 javac 根据程序的上下文,

* 在后台推断出了参数的类型。 Lambda 表达式的类型依赖于上下文环境,是由编译器推断出来的。这就是所谓的 “类型推断”

*/

// 04 Lambda 表达式的参数列表的数据类型可以省略不写,因为JVM编译器通过上下文推断出,数据类型,即“类型推断”

Comparator<Integer> integerComparator01 = ( Integer x, Integer y) -> Integer.compare(x, y);

System.out.println( integerComparator01.compare(6,5));

//还可以简化

Comparator<Integer> integerComparator02 = ( x, y) -> Integer.compare(x, y);

System.out.println( integerComparator02.compare(3,5));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值