Java 8 Stream API 將集合操作從「如何做」(命令式)提升為「做什麼」(聲明式)。本文通過對比傳統迴圈與 Stream 寫法,建立函數式集合處理的直觀認知。
需求:從名字列表中篩選長度 > 3 的名字,轉大寫,收集為新列表。
List<String> result = new ArrayList<>();
for (String name : names) {
if (name.length() > 3) {
result.add(name.toUpperCase());
}
}
List<String> result = names.stream()
.filter(name -> name.length() > 3)
.map(String::toUpperCase)
.collect(Collectors.toList());
collection.stream()、Arrays.stream(array)、Stream.of(...)filter(Predicate) 篩選map(Function) 轉換flatMap(Function) 扁平化distinct() 去重sorted(Comparator) 排序limit/skip 截取collect(Collector) 收集forEach(Consumer) 遍歷reduce 歸約count/min/max 聚合anyMatch/allMatch/noneMatch 判斷// 串行
names.stream().filter(...).map(...).collect(...);
// 並行(多核自動分片)
names.parallelStream().filter(...).map(...).collect(...);
注意:並行流有線程池開銷,小數據量反而較慢;有狀態操作(如 limit)並行效果不穩定。
| 誤區 | 正確認知 |
|---|---|
| Stream 可復用 | Stream 只能消費一次,再用需重新創建 |
| 中間操作立即執行 | 惰性求值,終端操作才觸發 |
| forEach 內修改外部變量 | 禁止副作用,用 collect/reduce 替代 |
| parallelStream 總是更快 | 需數據量大、CPU 密集、無共享狀態 |
List<String> words = Files.lines(Paths.get("article.txt"))
.flatMap(line -> Arrays.stream(line.split("\\W+")))
.filter(w -> !w.isEmpty())
.map(String::toLowerCase)
.collect(Collectors.groupingBy(w -> w, Collectors.counting()))
.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed())
.limit(10)
.collect(Collectors.toMap(
Map.Entry::getKey, Map.Entry::getValue,
(a, b) -> a, LinkedHashMap::new
));
Stream API 以 filter-map-collect 為核心模式,配合 flatMap、groupingBy 等進階收集器,能用流水線風格表達複雜集合邏輯。掌握「惰性中間操作 + 終端觸發」模型,是寫出高性能 Stream 代碼的關鍵。下一篇將深入 MapReduce 模式與 reduce 歸約操作。