Java 中的 Lambda 表达式 是 Java 8 引入的,用来简化**函数式接口(只有一个抽象方法的接口)**的实现。
下面从基本语法 → 常见用法 → 示例一步步说明。
(参数列表) -> { 方法体 }
Runnable r = () -> System.out.println("Hello Lambda");
r.run();
等价于:
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello Lambda");
}
};
Consumer<String> c = s -> System.out.println(s);
c.accept("Hello");
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
System.out.println(add.apply(2, 3));
| 接口 | 方法 | 说明 |
|---|---|---|
Runnable |
run() |
无参无返回值 |
Consumer<T> |
accept(T) |
有参无返回值 |
Supplier<T> |
get() |
无参有返回值 |
Function<T,R> |
apply(T) |
有参有返回值 |
Predicate<T> |
test(T) |
有参返回 boolean |
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> result = nums.stream()
.filter(n -> n > 1)
.map(n -> n * 2)
.collect(Collectors.toList());
list.forEach(System.out::println);
等价:
list.forEach(s -> System.out.println(s));
常见形式:
对象::方法类::静态方法类::实例方法类::new@FunctionalInterface
interface MyInterface {
int calculate(int a, int b);
}
MyInterface mi = (a, b) -> a + b;
System.out.println(mi.calculate(2, 3));
Lambda = 参数 -> 行为,用来简化函数式接口的实现
如果你愿意,我可以:
你想从哪方面继续?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。