Lambda表达式的一些简单用法

(个人笔记:可能有不严谨之处)
Lambda 表达式使用起来很简洁,在使用的时候可以省去方法名,
正因如此也有一些限制:要求接口只有一个抽象方法(可以有其他如default,static方法)
语法: (参数1,参数2,…)->{}

public class Practice_Lambda{
	public static void main(String[] args){
// ①接口普通用法
		IEat ieat = new Dog();
		ieat.eat();
// ②匿名类用法		
		IEat ieat2 = new IEat(){
			public void eat(){
				System.out.println("不爱吃骨头");
			}	
		};
		ieat2.eat();
		
//③Lambda用法一(无参):一句代码时可以省去大括号,多句代码时必须加上大括号                                                                  
		IEat ieat3 = ()->{System.out.println("爱吃骨头和青菜");};
		ieat3.eat();
//lambda用法二(有参):可以省去参数类型		
		IRun irun1 = (speed,unit) -> {System.out.println("每小时跑"+speed+unit);};
		irun1.run(3,"公里");
//lambda用法三(返回值):如果有多句代码,则必须写上大括号和return
		ICount icount = (nums) -> nums ;
		System.out.println(icount.count(5)+"只小狗");
//lambda用法三(参数中使用final):
		IAppearance iappearance = (nums,color)-> color;
		System.out.println(iappearance.appearance(2,"黄色")+"小狗");
	}
}
//无参的接口
interface IEat{
	public void eat();	
}
class Dog implements IEat{
	public void eat(){
		System.out.println("吃骨头");
	}	
}
//有参的接口
interface IRun{
	public void run(int speed,String unit);	
}
//有返回值的方法
interface ICount{
	public int count(int nums);
} 
//final修饰参数的方法
interface IAppearance{
	public String appearance(final int nums,final String color);
}

下面是结果

java "Practice_Lambda"
Process started (PID=1716) >>>
吃骨头
不爱吃骨头
爱吃骨头和青菜
每小时跑3公里
5只小狗
黄色小狗
<<< Process finished (PID=1716). (Exit code 0)
================ READY ================

测试了一下只有一个抽象方法但有其他方法的Lambda表达式,可以运行,如下

class Test_Lambda{
	public static void main(String[] args){
		IABC iabc = ()-> System.out.println("测试");
		iabc.abc();
		
	}
}

interface IABC{
	public void abc();
//默认方法	
	public default void abc2(){
		System.out.println("default 方法");
	}
//静态方法	
	public static void abc3(){
		System.out.println("static 方法");
	}	
}

下面是运行结果

java "Test_Lambda"
Process started (PID=16332) >>>
测试
<<< Process finished (PID=16332). (Exit code 0)
================ READY ================
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值