java.util.stream Interface 自 JDK 8 / JDK 24 Gatherers 引入

Stream

声明式函数数据流管道接口,支持惰性中间操作(filter/map/flatMap/gather)与终端归约操作(toList/collect/reduce)。

类签名与继承体系

Declaration
public interface Stream<T> extends BaseStream<T, Stream<T>>
继承 / 实现关系: AutoCloseable -> BaseStream -> Stream<T>

设计原理与核心定位

Stream 并不存储数据,而是对数据源(集合、数组、文件行、生成器)定义一套惰性求值管道。只有在调用终端操作(如 toList()、collect())时才会一次性融合遍历,避免产生大量中间临时集合。

JDK 16 引入的 toList() 极大简化了收集代码;JDK 24/25 正式转正的 Stream Gatherers(gather()) 更支持固定窗口分组、滑动窗口与自定义有状态中间操作。

核心属性与常量

属性 / 常量 修饰符与类型 说明与作用
Intermediate Ops 惰性操作 filter、map、flatMap、distinct、sorted、peek、limit、gather,仅记录操作链不立即计算。
Terminal Ops 终端触发 toList、collect、forEach、reduce、count、anyMatch、findFirst,触发流消费且流不可复用。

常用方法详解

方法签名 返回值 复杂度 / 并发特性 功能说明
filter(Predicate<? super T>) Stream<T> 无状态惰性 按断言筛选符合条件的元素。
map(Function<? super T, ? extends R>) Stream<R> 一对一映射 将元素转换为另一种类型。
flatMap(Function<T, Stream<R>>) Stream<R> 扁平化展开 将嵌套集合或一对多流展平为单层流。
toList() List<T> JDK 16+ 不可变 比 collect(Collectors.toList()) 更简洁且内存更紧凑,返回不可修改列表。
collect(Collectors.groupingBy(...)) Map<K, ...> 分组聚合 按维度分组、统计求和或构建键值映射。
gather(Gatherer) Stream<R> JDK 24/25 新特性 通过 Gatherers.windowFixed(n) 等实现滑动/固定批处理窗口。

完整示例代码

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class StreamPipelineDemo {
    record Task(String module, int costMs, boolean success) {}

    public static void main(String[] args) {
        List<Task> tasks = List.of(
                new Task("auth", 35, true),
                new Task("order", 120, true),
                new Task("order", 80, false),
                new Task("ai-rag", 240, true)
        );

        Map<String, Double> avgCostByModule = tasks.stream()
                .filter(Task::success)
                .collect(Collectors.groupingBy(
                        Task::module,
                        Collectors.averagingInt(Task::costMs)
                ));
        System.out.println(avgCostByModule);
    }
}

生产避坑与现代 JDK 最佳实践

  • Collectors.toMap 重复键异常:未提供合并函数时遇到重复 Key 会抛 IllegalStateException,务必传入第三参数如 (oldV, newV) -> newV。
  • 流只能消费一次:对同一 Stream 变量二次调用终端操作会抛出 IllegalStateException: stream has already been operated upon。
  • 慎用 parallelStream():底层共用公共 ForkJoinPool,严禁在并行流中执行数据库或 HTTP 阻塞调用。

相关核心类推荐