Lambda 与 Stream
lambda、stream-api、optionals。
35 分钟
Lambda 与 Stream
java-fundamentals 用循环处理集合——本课引入 Lambda、Stream API 与 Optional,用声明式写法过滤、映射与聚合数据。
学习目标
- 编写函数式接口与 Lambda 表达式
- 用 Stream 完成 filter / map / reduce 管道
- 用 Optional 表达「可能缺失」的返回值
Lambda 与函数式接口
@FunctionalInterface
public interface SlugFilter {
boolean test(String slug);
}
SlugFilter coreOnly = slug -> slug.startsWith("jvc-");
List<String> slugs = List.of("jvc-types", "java-oop", "jvc-control");
slugs.stream().filter(coreOnly::test).forEach(System.out::println);
| 内置接口 | 方法 | 用途 |
|---|---|---|
Predicate<T> | test | 过滤 |
Function<T,R> | apply | 映射 |
Consumer<T> | accept | 消费 |
Supplier<T> | get | 供给 |
方法引用:System.out::println、String::length、this::validate。
Stream 管道
record LessonView(String slug, int order) {}
List<LessonView> views = lessons.stream()
.filter(l -> l.order() > 0)
.sorted(Comparator.comparing(Lesson::order))
.map(l -> new LessonView(l.slug(), l.order()))
.toList(); // JDK 16+ 不可变列表
int totalMinutes = lessons.stream()
.mapToInt(Lesson::durationMinutes)
.sum();
- Stream 不存储元素,一次终端操作消费管道
- 惰性:中间操作遇终端才执行
- 并行流
parallelStream()需无共享可变状态(见 jvc-concurrency)
Optional
public Optional<Lesson> findBySlug(String slug) {
return Optional.ofNullable(bySlug.get(slug));
}
findBySlug("jvc-functional")
.map(Lesson::title)
.orElse("未找到");
// 避免
Lesson l = findBySlug("x").get(); // 空则 NoSuchElementException
用 orElseGet(Supplier) 延迟构造默认值;不要用 Optional 作字段或集合元素。