Lambda表达式是什么?
一种简洁的匿名函数,用来快速表示一段可执行代码(函数),常在集合遍历、接口回调中使用
注意:
Lambda表达式只作用于函数式接口(有且只有一个抽象方法的接口)
语法:
点击查看代码
(参数列表) -> { 方法体 }
- 无参数:() ->
- 单个参数:可省略括号 x ->
- 方法体只有一行:可省略大括号、return
代码示例:
- 自定义函数式接口
点击查看代码
// 函数式接口(只有1个抽象方法)
@FunctionalInterface
interface Say {
void hello(String name);
}
点击查看代码
public class LambdaDemo {
public static void main(String[] args) {
// 1. 传统匿名内部类写法
Say s1 = new Say() {
@Override
public void hello(String name) {
System.out.println("你好:" + name);
}
};
s1.hello("小明");
// 2. Lambda 简化写法
Say s2 = name -> System.out.println("你好:" + name);
s2.hello("小红");
}
}
输出:
点击查看代码
你好:小明
你好:小红
- 无参数
点击查看代码
@FunctionalInterface
interface Run {
void run();
}
点击查看代码
public class Test {
public static void main(String[] args) {
Run r = () -> System.out.println("跑起来啦");
r.run();
}
}
输出:
点击查看代码
跑起来啦
- 带返回值
点击查看代码
@FunctionalInterface
interface Calc {
int add(int a, int b);
}
点击查看代码
public class Test {
public static void main(String[] args) {
// 完整写法(不省略任何符号)
Calc c1 = (a, b) -> {
return a + b;
};
// 简写写法(单行表达式,省略 {}、return、末尾分号)
Calc c2 = (a, b) -> a + b;
System.out.println(c1.add(3, 5)); // 8
System.out.println(c2.add(3, 5)); // 8
}
}
省略规则:
- 方法体只有一行代码:可去掉 {}
- 这一行恰好是返回值表达式:可同时去掉 return
- 多行代码:{} 和 return 都不能省
输出:
点击查看代码
8
以遍历集合为例:
点击查看代码
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Lambda");
// Lambda 遍历
list.forEach(str -> System.out.println(str));
}
}
输出:
点击查看代码
Java
Lambda
浙公网安备 33010602011771号