Java Stream API:函数式流水线处理

一、Stream 是什么

Stream 是对集合的函数式流水线处理:数据源 → 中间操作(惰性)→ 终止操作(触发)。不修改原集合,强调”做什么”而非”怎么做”。

二、常用操作

List<Integer> nums = Arrays.asList(1,2,3,4,5);
int sum = nums.stream()
    .filter(n -> n % 2 == 0)     // 中间:过滤
    .map(n -> n * n)            // 中间:转换
    .reduce(0, Integer::sum);    // 终止:求和

三、常用 API

操作 说明
filter/map 过滤/转换
collect 收集成 List/Map/Set
sorted/distinct 排序/去重
count/sum/max 统计

并行流 parallelStream() 可利用多核,但注意线程安全与开销,别盲目用。