Lambda表达式

Lambda表达式

(第18天)

Lambda表达式的介绍:

1.Lambda表达式本质

是对象,是接口的实现类

2.Lambda表达式使用前提

实现的接口,必须是一个函数式接口,接口中只有一个抽象方法

3.Lambda表达式优势:

比匿名内部类的实现更加简化

 

Lambda表达式的实现

1.语法结构:  (参数列表)->(方法体)

2.定义出一个函数式接口,接口中只能含有一个抽象方法,使用注解@Functionallnterface验证接口是否为函数式接口

 

典型例题

第一题:

Lambda表达式使用

{
public static void main(String[] args){
 //使用Lambda表达式实现接口MyInter
MyInter my = ()->{System.out.println("Lambda表达式实现的接口");}
my.fun();  //Lambda表达式实现的接口
}
}

@FunctionalIiterface
interface MyInter{
    void fun();
}

第二题:

   定义一个函数式接口CurrentTimePrinter,其中抽象方法void printCurrentTime(), 函数式接口要求使用lambda表达式实现,
   在测试类中定义static void showLongTime(CurrentTimePrinter time),该方法的预期行为是使用参数time打印出系统当前毫秒值
   测试showLongTime()方法

public class 作业3 {

	public static void main(String[] args) {
		IntCalc ic = (a,b)->a*b;
		getProduct(2,3,ic);
		//getProduct(2,3,(a,b)->a*b);
	}	
		static void getProduct(int a,int b,IntCalc calc) {
			
			int product = calc.calc(a, b);
			System.out.println(product);
			
		}
	
}
@FunctionalInterface
interface IntCalc{
	int calc(int a,int b);
}

 

第三题:

 定义一个函数式接口IntCalc,其中抽象方法int calc(int a , int b), 函数式接口要求使用lambda表达式实现,
在测试类中定义static void getProduct(int a , int b ,IntCalc calc), 该方法的预期行为是使用参数calc得到a和b的乘积并打印结果
测试getProduct()

public class 作业2 {

	public static void main(String[] args) {
		 
		 //无参数-->获取当前毫秒值并输出
		//函数式接口要求使用lambda表达式实现
		 CurrentTimePrinter ct = ()->System.out.println(System.currentTimeMillis());
		 //  测试showLongTime()方法
		 showLongTime(ct);


	}
	static void showLongTime(CurrentTimePrinter time) {
		//  该方法的预期行为是使用参数time打印出系统当前毫秒值
		time.printCurrentTime();

	}
}
@FunctionalInterface
interface CurrentTimePrinter {
	void printCurrentTime();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值