示例
首先定义一个接口,使用该接口来演示Lambda是如何使用的。
package cn.unuuc.java.service;public interface OrderService {void get();}
匿名内部类实现接口
@Testpublic void test02(){OrderService orderService = new OrderService() {@Overridepublic void get() {System.out.println("get.......");}};orderService.get();}
也可以省略掉示例名 名称
public void test03(){new OrderService() {@Overridepublic void get() {System.out.println("get.......");}}.get();}

可以看到 new OrderService() 代码为灰色的,并且鼠标移动在上会提示一些操作,点击将这段代码自动转换为Lambda表达式。
@Testpublic void test03(){((OrderService) () -> System.out.println("get.......")).get();}
可能idea转换的一开始看不太懂。看一下下面的代码
// 首先将 () -> System.out.println("get.......") 看作是一个整体,// 将其转换为 OrderService 类型,(OrderService)() -> System.out.println("get.......")// 在将 OrderService 类型,(OrderService)() -> System.out.println("get.......") 看作一个整体,讲个括号// 最后在调用该对象中的方法:((OrderService) () -> System.out.println("get.......")).get();@Testpublic void test03(){OrderService orderService = () -> System.out.println("get.......");orderService.get();}
Lambda表达式规范
一句话:
使用Lambda表达式依赖于函数式接口(只有一个抽象方法的接口为函数式接口,无论是否存在注解@FunctionalInterface)。
什么是函数式接口见前一篇文章
Lambda表达式语法
- () 参数列表(参数名不能重复)
- -> 分割
- {} 方法体
实例:
(a,b)->{}
无参方法调用
定义函数接口
package cn.unuuc.java.fun;@FunctionalInterfacepublic interface FunctionInterface01 {void hello();}
测试方法
@Testpublic void test04(){// 匿名内部类new FunctionInterface01() {@Overridepublic void hello() {System.out.println("hello......");}}.hello();// Lambda表达式FunctionInterface01 functionInterface01 = ()->{System.out.println("Lambda hello......");};functionInterface01.hello();}
有参方法 返回值 调用
定义函数接口
package cn.unuuc.java.fun;@FunctionalInterfacepublic interface FunctionInterface02 {String get(int i,int j);}
测试方法
@Testpublic void test05(){// 匿名内部类String s = new FunctionInterface02() {@Overridepublic String get(int i, int j) {return i + "--" + j;}}.get(10, 20);System.out.println(s);// Lambda 表达式FunctionInterface02 functionInterface02 = (i,j)->{return i + "--" + j;};String s1 = functionInterface02.get(10, 20);System.out.println(s1);}
Lambda表达式简化
@Testpublic void test07(){// 精简的代码((FunctionInterface02)(i,j)-> {return i + "--" + j;}).get(10,20);}
((FunctionInterface02)(i,j)-> {return i + "--" + j;}).get(10,20);
而如果对于方法体里只有一条语句,那么 { } 是可以省略掉的
@Testpublic void test07(){((FunctionInterface01)()-> System.out.println("hello")).hello();}
如果存在返回值的方法而方法体里只有一条语句,则return关键字也可以省略
@Testpublic void test07(){// 精简的代码((FunctionInterface02)(i,j)-> i+"--"+j).get(10,20);}
