Java进阶-Java Stream API

Java进阶—一篇文章搞懂Stream API

最近整理之前留下的笔记,发现对于Stream API 这块记录的比较零散,也没有系统整理过,正好最近做的一个项目里面也用了大量Stream相关的API。也借此次机会也顺带把Stream API搞懂并记录成笔记。以下仅为个人理解,有误区的地方欢迎各位大佬批评指正!

首先我们要明白Stream 是什么?

总的来说,Stream API 是 JDK 8 最重量级的新特性,它把"对数据的操作"从命令式(怎么做的循环)升级为声明式(做什么的表达)。也就是说,JDK8之前的版本是不支持这种流式操作的。这篇文章从概念、创建、中间操作、终端操作、Collectors 收集器、并行流一路讲到案例和踩坑指南。

前言

先感受一下 Stream 的价值。需求:从员工列表中筛选出工资大于 8000 的员工,按工资降序,取前 3 名的名字。

传统写法(命令式,关注"怎么做"):

List<Employee> temp = new ArrayList<>();
for (Employee e : employees) {
    if (e.getSalary() > 8000) {
        temp.add(e);
    }
}
temp.sort(new Comparator<Employee>() {
    @Override
    public int compare(Employee a, Employee b) {
        return Double.compare(b.getSalary(), a.getSalary());
    }
});
List<String> names = new ArrayList<>();
for (int i = 0; i < 3 && i < temp.size(); i++) {
    names.add(temp.get(i).getName());
}

Stream 写法(声明式,只描述"做什么"):

List<String> names = employees.stream()
        .filter(e -> e.getSalary() > 8000)                  // 筛选
        .sorted(Comparator.comparingDouble(Employee::getSalary).reversed()) // 排序
        .limit(3)                                            // 截取
        .map(Employee::getName)                              // 提取
        .collect(Collectors.toList());                       // 收集

一行链式调用,逻辑像"流水线"一样从上往下读就是业务语义。这就是 Stream 的核心价值:用声明式的链式表达替代命令式的循环控制,代码更短、意图更清晰、更容易并行化。


一、Stream 是什么?先纠正三个误解

Stream(流)是数据源的一个视图,和对数据进行一系列计算的操作管道****,不是一种数据结构。

1.1 三个重要特征

  1. 不存储数据:它只是数据源(集合、数组、IO 等)上的一个计算管道,本身不保存元素;
  2. 不修改数据源:filter、sorted 等操作都会返回新的流/结果,原来的集合纹丝不动;
  3. 惰性执行 + 一次性消费:中间操作不会立即执行,碰到终端操作才"开闸放水";而且一个流只能被消费一次,用完就废。

1.2 三个常见误解

  • 误解一:Stream 是 IO 流? 完全不是。java.io 的流负责读写文件/网络,java.util.stream 的流负责对数据的计算,两者只是撞名了;
  • 误解二:Stream 是集合? 不是。集合存数据(内存结构),流做计算(管道)。流用完就没了,集合可以反复遍历;
  • 误解三:Stream 一定更快? 不一定。它的优势是表达力和并行化,纯循环性能在简单场景往往更好(后面性能章节详说)。

1.3 一个直观的流水线模型

以"过滤偶数 → 平方 → 收集"为例,数据在流水线中各阶段的形态如下:

// 对应代码:Stream.of(1, 2, 3, 4, 5)
//           .filter(i -> i % 2 == 0)
//           .map(i -> i * i)
//           .collect(Collectors.toList());   // 结果: [4, 16]

image

图 1:Stream 流水线模型——绿色为中间操作(惰性、可链式),橙色为终端操作(触发执行),紫色回流箭头表示惰性求值:终端操作出现才从源头拉取数据


二、创建 Stream 的 6 种常用方式

public class CreateStreamDemo {
    public static void main(String[] args) throws IOException {
        // 1. 从集合创建(最常用)
        List<String> list = Arrays.asList("a", "b", "c");
        Stream<String> s1 = list.stream();
        Stream<String> s2 = list.parallelStream();   // 并行流

        // 2. 从数组创建
        String[] arr = {"x", "y", "z"};
        Stream<String> s3 = Arrays.stream(arr);
        Stream<String> s4 = Stream.of("1", "2", "3");

        // 3. 三种基本数值流(避免装箱开销,自带 sum/max 等统计方法)
        // 注意:range 是左闭右开,rangeClosed 是左闭右闭
        IntStream is = IntStream.range(1, 101);         // 1 ~ 100(不含 101)
        IntStream is2 = IntStream.rangeClosed(1, 100);  // 1 ~ 100(含 100)
        long sum = is2.sum();                           // 5050
        System.out.println(sum);

        // 4. 无限流:iterate / generate(必须配合 limit 截断)
        Stream<Integer> odds = Stream.iterate(1, n -> n + 2).limit(5); // 1,3,5,7,9
        Stream<Double> randoms = Stream.generate(Math::random).limit(3);
        odds.forEach(System.out::print);   // 13579

        // 5. 从文件创建(每行一个元素,需要关闭,推荐 try-with-resources)
        try (Stream<String> lines = Files.lines(Paths.get("data.txt"))) {
            long lineCount = lines.count();
        }

        // 6. 从字符串分割创建(JDK 8)
        Pattern.compile(",").splitAsStream("a,b,c").forEach(System.out::print); // abc

        // 补充:Stream 还可以 concat 合并两个流
        Stream<String> merged = Stream.concat(s3, s4);
    }
}

提示:Files.lines、Arrays.stream 返回的流若关联了 IO 资源,需要用 try-with-resources 确保关闭;纯集合流则无需关心。


三、操作全景图:中间操作 vs 终端操作

Stream 的 API 分为两大类,这是理解它的骨架:

类别 特点 操作
中间操作 返回新 Stream,可以继续链式调用;惰性,不触发执行 filter、map、flatMap、distinct、sorted、peek、limit、skip、takeWhile(JDK9)、dropWhile(JDK9)
终端操作 返回结果(非 Stream)或产生副作用;触发整条流水线执行,流终结 collect、forEach、reduce、count、min、max、sum、average、findFirst、findAny、anyMatch、allMatch、noneMatch、toArray、iterator

再细分一层(帮助理解性能特征):

  • 无状态操作:filter、map、flatMap、peek——处理一个元素不依赖其他元素,可自由并行;
  • 有状态操作:distinct、sorted、limit、skip——需要看到全部/部分数据才能出结果(比如排序),并行代价更高。

四、中间操作详解

先准备一份贯穿全文的示例数据:

public class Employee {
    private String name;
    private String department;   // 部门
    private double salary;       // 工资
    private int age;
    private String city;

    public Employee(String name, String department, double salary, int age, String city) {
        this.name = name;
        this.department = department;
        this.salary = salary;
        this.age = age;
        this.city = city;
    }
    // getter/setter 省略...
    @Override
    public String toString() {
        return String.format("%s(%s,%.0f,%d,%s)", name, department, salary, age, city);
    }
}

List<Employee> employees = Arrays.asList(
        new Employee("张三", "开发", 9500, 26, "北京"),
        new Employee("李四", "开发", 12000, 32, "北京"),
        new Employee("王五", "测试", 7000, 24, "上海"),
        new Employee("赵六", "开发", 8500, 30, "深圳"),
        new Employee("孙七", "测试", 9200, 28, "上海"),
        new Employee("周八", "产品", 6000, 27, "北京"),
        new Employee("吴九", "产品", 6500, 35, "深圳"),
        new Employee("郑十", "测试", 7000, 24, "广州")
);

4.1 filter:过滤

// 筛选北京的员工
List<Employee> beijing = employees.stream()
        .filter(e -> "北京".equals(e.getCity()))
        .collect(Collectors.toList());
// [张三, 李四, 周八]

4.2 map:一对一转换

// 提取所有员工姓名
List<String> names = employees.stream()
        .map(Employee::getName)
        .collect(Collectors.toList());
// [张三, 李四, 王五, 赵六, 孙七, 周八, 吴九, 郑十]

// 对元素本身做计算:所有姓名转大写并加编号
List<String> upper = Stream.of("foo", "bar", "baz")
        .map(String::toUpperCase)
        .collect(Collectors.toList()); // [FOO, BAR, BAZ]

4.3 flatMap:一对多展开(拍平)

map 是"一个进一个出",flatMap 是"一个进、拆成多个出、再把所有结果摊平成一个流":

// 场景 1:拍平嵌套集合
List<List<Integer>> nested = Arrays.asList(
        Arrays.asList(1, 2, 3),
        Arrays.asList(4, 5),
        Arrays.asList(6, 7, 8, 9));

List<Integer> flat = nested.stream()
        .flatMap(List::stream)
        .collect(Collectors.toList());
// [1, 2, 3, 4, 5, 6, 7, 8, 9]

// 场景 2:一句话拆成单词(经典词频统计的前半段)
List<String> sentences = Arrays.asList("hello world", "hello stream", "hi java");
List<String> words = sentences.stream()
        .flatMap(sentence -> Arrays.stream(sentence.split(" ")))
        .collect(Collectors.toList());
// [hello, world, hello, stream, hi, java]

4.4 distinct:去重

// 按城市去重(依赖 equals/hashCode,String 天然支持)
List<String> cities = employees.stream()
        .map(Employee::getCity)
        .distinct()
        .collect(Collectors.toList());
// [北京, 上海, 深圳, 广州]

注意:对自定义对象去重,必须重写该对象的 equals() 和 hashCode(),distinct 只认这两个方法。

4.5 sorted:排序

// 自然排序
Stream.of(5, 3, 1, 4, 2).sorted().forEach(i -> System.out.print(i + " "));
// 1 2 3 4 5

// Comparator 定制排序:工资降序,工资相同按年龄升序
List<Employee> sorted = employees.stream()
        .sorted(Comparator
                .comparingDouble(Employee::getSalary).reversed()
                .thenComparingInt(Employee::getAge))
        .collect(Collectors.toList());
// [李四(12000), 张三(9500), 孙七(9200), 赵六(8500), 王五/郑十(7000,同龄按插入序)...]

Comparator 的组合器速记:comparing / comparingDouble / comparingInt → .reversed() 反转 → .thenComparing(...) 次级条件,可一直链下去。

4.6 limit / skip:截断与跳过

// 工资最高的前 3 名
List<Employee> top3 = employees.stream()
        .sorted(Comparator.comparingDouble(Employee::getSalary).reversed())
        .limit(3)
        .collect(Collectors.toList());

// 跳过前 2 名,取后面的(常用于分页:skip((page-1)*size).limit(size))
List<Employee> rest = employees.stream()
        .skip(2)
        .limit(3)
        .collect(Collectors.toList());

4.7 peek:偷看一眼(仅用于调试)

// peek 会对每个元素执行操作并原样返回,属于中间操作
List<Integer> result = Stream.of(1, 2, 3, 4)
        .peek(i -> System.out.println("peek 看到了: " + i))
        .filter(i -> i % 2 == 0)
        .collect(Collectors.toList());
// 常用来观察流水线中途的数据,生产代码不要用它承担业务逻辑

4.8 takeWhile / dropWhile(JDK 9+)

// takeWhile:从开头一直取,直到条件第一次不成立就停止
Stream.of(1, 2, 3, 4, 1, 2).takeWhile(i -> i < 3).forEach(System.out::print); // 12

// dropWhile:从开头一直丢,条件第一次不成立后全部保留
Stream.of(1, 2, 3, 4, 1, 2).dropWhile(i -> i < 3).forEach(System.out::print); // 3412

注意它和 filter 的区别:filter 会扫完所有元素,takeWhile/dropWhile 是"遇到第一个不满足的就停",特别适合处理已按条件排好序的数据。


五、终端操作详解

5.1 匹配与查找

// 是否存在:开发部是否有工资超过 10000 的员工
boolean hasHighPaid = employees.stream()
        .anyMatch(e -> "开发".equals(e.getDepartment()) && e.getSalary() > 10000); // true

// 全部满足 / 全不满足
boolean allAdult = employees.stream().allMatch(e -> e.getAge() >= 18);   // true
boolean noMinor  = employees.stream().noneMatch(e -> e.getAge() < 18);   // true

// 查找第一个 / 任意一个
Optional<Employee> first = employees.stream().filter(e -> e.getSalary() > 9000).findFirst();
first.ifPresent(e -> System.out.println("第一个 9000+ 的是: " + e.getName())); // 张三

// findAny 在串行流中通常也返回第一个;在并行流中可能返回任意一个匹配项,性能更好
Optional<Employee> any = employees.parallelStream().filter(e -> e.getSalary() > 9000).findAny();

这类方法返回 Optional<T>,用于显式表达"结果可能不存在",避免返回 null 造成 NPE——ifPresent、orElse、orElseGet、orElseThrow 是处理它的四件套。

5.2 统计:count / min / max / sum / average

long count = employees.stream()
        .filter(e -> "开发".equals(e.getDepartment()))
        .count();   // 开发部人数:3

Optional<Employee> highest = employees.stream()
        .max(Comparator.comparingDouble(Employee::getSalary));
Optional<Employee> youngest = employees.stream()
        .min(Comparator.comparingInt(Employee::getAge));

// 数值流专属:sum / average / statistics(免装箱,性能更好)
IntSummaryStatistics stats = employees.stream()
        .mapToInt(Employee::getAge)
        .summaryStatistics();
System.out.println(stats.getMax());     // 最大年龄 35
System.out.println(stats.getAverage()); // 平均年龄 ~28.25
System.out.println(stats.getSum());     // 总和 226

5.3 reduce:归约(把流折叠成一个值)

// 三参数:初始值 + 累加器 + 并行合并器
int totalAge = employees.stream()
        .reduce(0, (sum, e) -> sum + e.getAge(), Integer::sum);

// 两参数(无初始值,返回 Optional,因为流可能为空)
Optional<Double> totalSalary = employees.stream()
        .map(Employee::getSalary)
        .reduce(Double::sum);

// 字符串拼接
String joined = Stream.of("a", "b", "c", "d")
        .reduce("", (acc, s) -> acc + s); // abcd(演示用;拼接首选 Collectors.joining)

reduce 是这些操作的"底层通用版"——count、sum 都可以用 reduce 表达。业务上优先用语义更明确的特化方法(count/sum/collect),reduce 更适合没有现成方法的自定义折叠逻辑。

5.4 forEach / forEachOrdered

// 串行流中两者一致;并行流中 forEach 不保证顺序,forEachOrdered 保证
employees.parallelStream().forEach(System.out::println);           // 顺序乱
employees.parallelStream().forEachOrdered(System.out::println);    // 顺序稳定

5.5 collect:最重要的终端操作

collect 是 Stream 的"出口",负责把流水线的结果收集成 List、Set、Map 或做分组聚合。它的重头戏是 Collectors 工具类,下一节专门展开。

List<String> list = stream.collect(Collectors.toList());           // JDK 8 通用
List<String> list2 = stream.toList();                              // JDK 16+ 更简洁(不可变)
Set<String> set = stream.collect(Collectors.toSet());
Collection<String> linked = stream.collect(Collectors.toCollection(LinkedList::new)); // 指定集合类型

六、Collectors 收集器详解(重头戏)

6.1 toList / toSet / toMap

List<String> names = employees.stream().map(Employee::getName).collect(Collectors.toList());

Set<String> cities = employees.stream().map(Employee::getCity).collect(Collectors.toSet());

// toMap(键映射, 值映射)
Map<String, Double> nameToSalary = employees.stream()
        .collect(Collectors.toMap(Employee::getName, Employee::getSalary));
// {张三=9500.0, 李四=12000.0, ...}

toMap 的两个经典坑(高频面试/线上事故点):

// 坑 1:key 重复 -> 直接抛 IllegalStateException: Duplicate key
// 郑十和王五都是"测试"?不,key 是姓名才重复。这里用城市做 key 就炸了:上海有两个人
Map<String, String> cityToName = employees.stream()
        .collect(Collectors.toMap(
                Employee::getCity,
                Employee::getName,
                (oldV, newV) -> oldV));   // 第三个参数:冲突时保留旧值(必须显式给)

// 坑 2:value 为 null -> NullPointerException
//        toMap 的 merge 基于 HashMap.merge,不允许 null value
//        如果 value 可能为 null,要么先 filter 掉,要么换 groupingBy 方案

6.2 joining:字符串拼接

String names = employees.stream()
        .map(Employee::getName)
        .collect(Collectors.joining(", "));           // 张三, 李四, 王五...

String wrapped = employees.stream()
        .map(Employee::getName)
        .collect(Collectors.joining(", ", "[", "]")); // [张三, 李四, 王五...]

6.3 groupingBy:分组(最强大)

一级分组——按部门分组:

Map<String, List<Employee>> byDept = employees.stream()
        .collect(Collectors.groupingBy(Employee::getDepartment));
// {开发=[张三,李四,赵六], 测试=[王五,孙七,郑十], 产品=[周八,吴九]}

分组 + 统计人数(下游收集器):

Map<String, Long> countByDept = employees.stream()
        .collect(Collectors.groupingBy(Employee::getDepartment, Collectors.counting()));
// {开发=3, 测试=3, 产品=2}

分组 + 求平均工资:

Map<String, Double> avgSalaryByDept = employees.stream()
        .collect(Collectors.groupingBy(
                Employee::getDepartment,
                Collectors.averagingDouble(Employee::getSalary)));
// {开发=10000.0, 测试=7733.33..., 产品=6250.0}

多级分组——先按部门,再按城市:

Map<String, Map<String, List<Employee>>> deptCity = employees.stream()
        .collect(Collectors.groupingBy(
                Employee::getDepartment,
                Collectors.groupingBy(Employee::getCity)));
// {开发={北京=[张三,李四], 深圳=[赵六]}, 测试={上海=[王五,孙七], 广州=[郑十]}, ...}

分组后对组内元素做转换(mapping):

// 部门 -> 姓名列表
Map<String, List<String>> namesByDept = employees.stream()
        .collect(Collectors.groupingBy(
                Employee::getDepartment,
                Collectors.mapping(Employee::getName, Collectors.toList())));
// {开发=[张三, 李四, 赵六], ...}

分组 + 收集后再处理(collectingAndThen):

// 每个部门工资最高的员工(先按部门分组,组内 maxBy,再从 Optional 里取出来)
Map<String, Employee> topByDept = employees.stream()
        .collect(Collectors.groupingBy(
                Employee::getDepartment,
                Collectors.collectingAndThen(
                        Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary)),
                        Optional::get)));
// {开发=李四(12000), 测试=孙七(9200), 产品=吴九(6500)}

6.4 partitioningBy:按布尔值分两组

分区是分组的特例:条件为 true 一组、false 一组,key 固定是 Boolean:

Map<Boolean, List<Employee>> partition = employees.stream()
        .collect(Collectors.partitioningBy(e -> e.getSalary() >= 9000));
// {true=[张三, 李四, 孙七], false=[王五, 赵六, 周八, 吴九, 郑十]}

// 分区 + 统计每组数量
Map<Boolean, Long> count = employees.stream()
        .collect(Collectors.partitioningBy(e -> e.getSalary() >= 9000, Collectors.counting()));
// {true=3, false=5}

6.5 汇总类收集器速查

Collectors.counting()                        // 计数
Collectors.summingInt / summingDouble        // 求和
Collectors.averagingInt / averagingDouble    // 平均
Collectors.maxBy(Comparator) / minBy(...)    // 最值(返回 Optional)
Collectors.summarizingDouble(...)            // 一次性拿到 count/sum/min/avg/max
Collectors.reducing(...)                     // 通用归约

七、串行流与并行流

7.1 怎么开启并行

employees.parallelStream()...        // 方式一:集合直接拿并行流
employees.stream().parallel()...     // 方式二:串行流转并行流(.sequential() 可转回)

并行流底层使用全局的 ForkJoinPool.commonPool(),默认线程数 = CPU 核心数 - 1。它把数据分片、多线程处理、再合并结果。

7.2 一个直观对比

long sum = LongStream.rangeClosed(1, 100_000_000)
        .parallel()          // 加这一个词:串行 ~100ms 级,并行可明显加速(机器相关)
        .sum();

7.3 并行流的四个坑(重要)

// 坑 1:在并行流里收集到非线程安全的集合 —— 结果丢失或抛异常
List<Integer> wrong = new ArrayList<>();
IntStream.rangeClosed(1, 1000).parallel().forEach(wrong::add);  // 反面教材!
// 正确做法:用 collect 收集,框架保证线程安全
List<Integer> right = IntStream.rangeClosed(1, 1000).parallel()
        .boxed().collect(Collectors.toList());

// 坑 2:修改共享变量 —— 竞态条件
long[] counter = {0};
IntStream.rangeClosed(1, 10000).parallel().forEach(i -> counter[0]++); // 结果不准!
// 正确做法:用 reduce / collect 归约,而非外部累加

// 坑 3:findAny / forEach 在并行流中不保证顺序(需要顺序用 forEachOrdered)

// 坑 4:数据量小、或操作很轻(比如纯装箱运算)时,并行反而更慢——线程调度和分片合并都有成本

适用经验:数据量大(万级以上)、单个元素处理较重(复杂计算/IO)、数据源易分片(ArrayList/数组好,LinkedList 差)、无共享状态——四个条件都满足再考虑并行流,否则默认串行。


八、惰性执行与短路:Stream 的执行原理

8.1 没有终端操作,中间操作一行都不会执行

List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream()
        .peek(s -> System.out.println("peek: " + s));  // 什么都不会打印!
// 缺少终端操作,整条流水线不会开闸

中间操作只是在"搭管道",记录每一步的 lambda,直到终端操作出现才一次性执行——这样框架可以做整体优化(比如短路、合并操作),而不是每一步都完整遍历一遍。

8.2 短路操作:找到就立刻停

// 只会打印 "filter: 1" "map: 1" "filter: 2" "map: 2" 然后停止
// findFirst 命中后,limit、filter 之后的元素直接不再处理
Optional<Integer> firstEven = Stream.of(1, 2, 3, 4, 5, 6)
        .peek(i -> System.out.println("filter: " + i))
        .filter(i -> i % 2 == 0)
        .peek(i -> System.out.println("map: " + i))
        .findFirst();
// 输出:filter: 1 / filter: 2 / map: 2  -> 结束,3~6 根本没碰

能短路的操作:limit、findFirst、findAny、anyMatch、allMatch、noneMatch。数据量大时,把能短路的操作放在链路合理位置收益明显。

8.3 一次性消费:流不能复用

Stream<String> s = Stream.of("a", "b", "c");
s.forEach(System.out::print);   // abc,正常
s.forEach(System.out::print);   // 抛 IllegalStateException: 
                                // stream has already been operated upon or closed

需要再处理一遍?从数据源重新 stream() 一个新流即可。


九、综合案例

案例 1:每个城市工资最高的员工

Map<String, Employee> topOfCity = employees.stream()
        .collect(Collectors.groupingBy(
                Employee::getCity,
                Collectors.collectingAndThen(
                        Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary)),
                        Optional::get)));
// {北京=李四, 上海=孙七, 深圳=吴九, 广州=郑十}

案例 2:词频统计(flatMap + groupingBy + counting)

Map<String, Long> wordCount = Stream.of("hello world", "hello java", "hi stream")
        .flatMap(s -> Arrays.stream(s.split(" ")))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// {hello=2, world=1, java=1, hi=1, stream=1}

案例 3:List 转 Map / Map 转 List

// List -> Map(name 为 key,employee 为 value)
Map<String, Employee> byName = employees.stream()
        .collect(Collectors.toMap(Employee::getName, Function.identity()));

// Map -> List(取出 value 排序)
List<Employee> sortedList = byName.values().stream()
        .sorted(Comparator.comparingDouble(Employee::getSalary).reversed())
        .collect(Collectors.toList());

案例 4:数组与流互转

int[] nums = {3, 1, 4, 1, 5, 9, 2, 6};
int[] sortedAsc = Arrays.stream(nums).sorted().toArray();   // 流回数组
int[] evens = Arrays.stream(nums).filter(n -> n % 2 == 0).toArray();

案例 5:笛卡尔积(两个流嵌套 flatMap)

List<String> sizes = Arrays.asList("S", "M", "L");
List<String> colors = Arrays.asList("红", "蓝");
List<String> products = sizes.stream()
        .flatMap(size -> colors.stream().map(color -> size + "-" + color))
        .collect(Collectors.toList());
// [S-红, S-蓝, M-红, M-蓝, L-红, L-蓝]

案例 6:生成有序编号(IntStream 与对象流拼接)

List<String> ranked = employees.stream()
        .sorted(Comparator.comparingDouble(Employee::getSalary).reversed())
        .map(Employee::getName)
        .collect(Collectors.toList());

IntStream.rangeClosed(1, ranked.size())
        .mapToObj(i -> "第" + i + "名: " + ranked.get(i - 1))
        .forEach(System.out::println);
// 第1名: 李四 / 第2名: 张三 / ...

十、常见坑与最佳实践清单

# 坑 / 建议 说明
1 流只能消费一次 重复使用抛 IllegalStateException,需要就从源头重建
2 Collectors.toMap key 冲突 必须传第三个参数 (v1, v2) -> v1 之类的合并函数,否则 Duplicate key 异常
3 Collectors.toMap value 为 null 直接 NPE,先 filter 或改用 groupingBy
4 自定义对象 distinct/sort 失效 检查 equals/hashCode(distinct)、compareTo(sorted)
5 别用 peek 写业务逻辑 peek 的定位是调试;有副作用的需求用 map + collect 或 forEach
6 IO 流记得关闭 Files.lines 等用 try-with-resources
7 数值计算优先用数值流 mapToInt/mapToDouble 避免装箱;boxed() 反向拆装
8 简单场景别硬套 Stream 一重简单循环用 for 语义更直接、性能更好;Stream 的价值在复杂链式处理
9 循环里反复创建流 把 .stream() 提到循环外,或改写管道结构
10 需要索引时 Stream 很别扭 IntStream.range + 下标取值,或老实用 for

十一、版本演进速览

版本 新增
JDK 8 Stream API 首发:全套中间/终端操作、Collectors、并行流
JDK 9 takeWhile / dropWhile;iterate 支持中断条件;ofNullable;Optional.stream()
JDK 16 stream.toList()(返回不可变 List,替代 collect(toList()));mapMulti(flatMap 的轻量替代)
// JDK 9:带终止条件的 iterate(生成 10 以内的偶数)
IntStream.iterate(0, i -> i < 10, i -> i + 2).forEach(System.out::print); // 02468

// JDK 9:ofNullable,null 时得到空流而不是 NPE
Stream.ofNullable(System.getProperty("noexist"))
      .forEach(System.out::println);   // 什么都不输出,长度 0

// JDK 16:直接 toList
List<String> list = Stream.of("a", "b").toList();

十二、总结

用三句话收束全文:

  1. 心智模型:Stream 是一条"数据流水线"——创建(source)→ 中间操作(返回新流,惰性搭管道)→ 终端操作(开闸放水,产出结果),流本身不存数据、不改源头、只能用一次;
  2. API 主线:中间操作背 8 个词(filter / map / flatMap / distinct / sorted / peek / limit / skip),终端操作抓 3 类(聚合 reduce/count/max、查找匹配 find/match、收集 collect),其中 collect + Collectors(分组 groupingBy、分区 partitioningBy、转集合 toMap/toList、拼接 joining)是日常使用频率最高的部分;
  3. 工程判断:追求表达力和复杂链式处理用 Stream;简单遍历用 for;并行流只在"数据量大 + 单元素处理重 + 无共享状态"时启用,并牢记 toMap 冲突、流不可复用这两大高频坑。

从"会写"到"写好"的路径:把文中员工数据的案例亲手敲一遍,再尝试用 Stream 重构自己项目里的一个 for 循环。这一套下来,Stream API 就真正处于会用,怎么用的阶段了。如果想更深入理解,推荐能力强的伙伴去看一下Stream的底层源码。


参考:

  • Java 官方文档:Package java.util.stream
  • 《Java 8 实战》(Java 8 in Action)第 4~7 章——Stream 章节的经典教材
posted @ 2026-09-29 17:36  Star丶呢喃  阅读(15)  评论(0)    收藏  举报