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();
}