java8新特性之一lambda

java8新特性之一lambda

lambda结合函数式接口使用,函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。

lambda四大重要特性

1 可选类型声明

不需要声明参数类型,即直接可以写参数,不需要声明类型,编译器可以自动识别类型

2 可选的参数圆括号

一个参数可以不要圆括号,多个参数需要圆括号

3 可选的大括号

在实现方法中,主体如果只有一个语句,可以不用写大括号,类似于if…else…的,可以不用写大括号

4 可选的返回关键字

如果主体返回值只有一个表达式,编译器会自动变异返回值,大括号能可以指明返回的类型

lambda简单示例

1 省略参数类型,返回值为5
() -> 5
2 省略参数类型,返回值用到参数
(x) -> 2*x
3 添加参数类型
(int x,int y)-> x+y
4 返回值可以为void
(String str) -> System.out.print(str)

package com.fxs.lambda;

public class Test {
	public static void main(String[] args) {
		Test1 test1 = () -> 5;
		System.out.println(test1.count());
		//参数类型可加可不加
		Test2 test2 = (x)-> 2*x;
		System.out.println(test2.count(2));
		Test3 test31 = (int x,int y) -> x+y;
		Test3 test32 = (x,y) -> x+y;
		Test3 test33 = (x,y) -> {return x+y ;};
		System.out.println(test31.count(2,3));
		//可以没有返回值
		Test4 test4 = (s)-> System.out.println(s);
		test4.count("测试无返回值");
	}
	
}
//函数式接口,有且只有一个抽象方法
@FunctionalInterface
interface Test1{
	public int count();
} 
interface Test2{
	public int count(int x );
}
interface Test3{
	public int count(int x,int y );
}
interface Test4{
	public void count(String str );
}

变量作用域

lambda 表达式只能引用标记了 final 的外层局部变量,这就是说不能在 lambda 内部修改定义在域外的局部变量,否则会编译错误。

interface Test5{
	public int count(int a);
}

//变量域 ,注意点1
final int num =1;
Test5 test5 = (x) -> x + num;
System.out.println(test5.count(2));
//num = 2; //把注释放开会报错,因为lambda表达式中用到num,如果num做修改,test5的实现类就不明确,编译错误,必须定义为final



//变量域,注意点2
int num1 =1;
Test5 test51 = (x) -> x + num1;
System.out.println(test5.count(2));
//num1 = 2;//lambda 表达式的局部变量可以不用声明为 final,但是必须不可被后面的代码修改(即隐性的具有 final 的语义)
//lambda 表达式的局部变量可以不用声明为 final,但是必须不可被后面的代码修改(即隐性的具有 final 的语义)

//变量域,注意点3
//String str="变量名不可重复";//注释放开会报错,因为局部变量str和lambda中的参数名str一样会报错
Test4 Test4 = (str) -> System.out.println(str);

菜鸟教程资料

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

随便男是我

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值