CodeRoadMap
首页路线题库资源库文章社区
CodeRoadMap

程序员的学习成长路线图。内容免费开放,登录后可同步路线图与课时进度。

由 程序员柏风 独立维护 · 关于作者

学习

  • 路线图
  • 课程
  • 面试题
  • 文章
  • 我

更多

  • 资源
  • 社区
  • 关于作者
  • 内容说明

© 2026 CodeRoadMap

津ICP备2026012044号-1·津公网安备12011002026155号·coderoadmap@126.com
Java 核心深化/课时/Lambda 与 Stream
RawBlame
课时目录12 节

Java 核心深化

  1. 01Java 核心地图
  2. 02类型与变量
  3. 03控制流
  4. 04类与对象
  5. 05抽象与接口
  6. 06集合框架
  7. 07Lambda 与 Stream
  8. 08并发基础
  9. 09I/O 与 NIO
  10. 10构建工具
  11. 11测试与 JUnit
  12. 12综合练习

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 作字段或集合元素。

与进阶课的关系

jva-methods 会讲方法引用与 Builder 链;jva-concurrency 用 CompletableFuture 组合异步 Stream 结果。

练习

  • 用 Stream 统计 slug 以 jvc- 开头的课时数量
  • 用 groupingBy 按首字母分组 slug
  • 把 if (x != null) 改为 Optional 链式调用

小结

Lambda 传行为,Stream 管流水线,Optional 显式缺失。 下一课并发基础:线程与虚拟线程。

加载本节练习…
← 上一课集合框架下一课 →并发基础