在 Java 中,Lambda 表达式是从 Java 8 开始引入的,用于简化**函数式接口(只有一个抽象方法的接口)**的实现。
下面从 概念 → 语法 → 常见用法 → 示例 一步步说明。
Lambda 本质上是一个匿名函数,用来替代匿名内部类,让代码更简洁。
✅ 使用前提:只能用于函数式接口
@FunctionalInterface
interface MyInterface {
void show();
}
(参数列表) -> { 方法体 }
// 无参数
() -> System.out.println("Hello");
// 一个参数
x -> x * 2;
// 多个参数
(a, b) -> a + b;
// 多行代码
(x, y) -> {
int sum = x + y;
return sum;
};
传统写法:
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程执行");
}
}).start();
Lambda 写法:
new Thread(() -> System.out.println("线程执行")).start();
List<String> list = Arrays.asList("A", "B", "C");
list.forEach(s -> System.out.println(s));
或更简洁:
list.forEach(System.out::println);
List<Integer> nums = Arrays.asList(3, 1, 2);
nums.sort((a, b) -> a - b);
List<Integer> list = Arrays.asList(1, 2, 3, 4);
list.stream()
.filter(n -> n % 2 == 0)
.forEach(n -> System.out.println(n));
@FunctionalInterface
interface Calculator {
int calc(int a, int b);
}
public class Test {
public static void main(String[] args) {
Calculator add = (a, b) -> a + b;
System.out.println(add.calc(3, 5));
}
}
// 对象::方法
list.forEach(System.out::println);
// 类::静态方法
Function<String, Integer> f = Integer::parseInt;
✅ Lambda 中不能修改外部局部变量(必须是 final 或事实 final)
✅ Lambda 不是所有接口都能用,必须是函数式接口
✅ this 指向外部类(和匿名内部类不同)
Lambda = 更简洁的函数式接口实现方式,常用于线程、集合、Stream。
如果你愿意,我也可以:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。