一、理論說明
1. 流的定義
Java 流(Stream)是 Java 8 引入的新特性,用于對集合(如 List、Set)或數組進行高效的聚合操作(如過濾、映射、排序)和并行處理。流不存儲數據,而是按需計算,支持鏈式調用,使代碼更簡潔、易讀。
2. 流與集合的區別
特性 | 集合(Collection) | 流(Stream) |
---|---|---|
數據存儲 | 存儲元素,占用內存 | 不存儲數據,按需計算 |
遍歷方式 | 外部迭代(手動 for/foreach) | 內部迭代(自動處理) |
一次性使用 | 可重復遍歷 | 只能消費一次(類似迭代器) |
延遲執行 | 立即執行 | 中間操作延遲,終止操作觸發執行 |
并行支持 | 需要手動實現多線程 | 直接支持并行流(parallelStream() ) |
二、流的創建與操作
1. 創建流
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;public class StreamExample {public static void main(String[] args) {// 1. 從集合創建List<String> list = Arrays.asList("a", "b", "c");Stream<String> stream = list.stream();// 2. 從數組創建String[] array = {"a", "b", "c"};Stream<String> arrayStream = Arrays.stream(array);// 3. 使用 Stream.of()Stream<String> ofStream = Stream.of("a", "b", "c");// 4. 創建無限流Stream<Integer> infiniteStream = Stream.iterate(0, n -> n + 2);infiniteStream.limit(5).forEach(System.out::println); // 輸出: 0, 2, 4, 6, 8}
}
2. 中間操作(返回新的流)
使用時需注意:流只能消費一次,消費后需重新創建。并行流適用于計算密集型任務,避免 I/O 操作。合理選擇中間操作和終止操作,避免過度使用復雜流。流 API 是 Java 8 最具影響力的特性之一,廣泛應用于數據處理、微服務、ORM 框架等場景。
- 過濾:
filter(Predicate<T>)
- 映射:
map(Function<T, R>)
- 排序:
sorted()
?或?sorted(Comparator<T>)
- 去重:
distinct()
- 截斷:
limit(long maxSize)
- 跳過:
skip(long n)
List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 5); List<Integer> evenNumbers = numbers.stream().filter(n -> n % 2 == 0) // 過濾偶數.distinct() // 去重.sorted() // 排序.collect(Collectors.toList()); // [2, 4]
3. 終止操作(觸發計算并關閉流)
- 聚合:
count()
,?max()
,?min()
- 匹配:
anyMatch()
,?allMatch()
,?noneMatch()
- 收集:
collect(Collectors.toList())
,?toSet()
,?toMap()
- 歸約:
reduce()
- 遍歷:
forEach()
List<String> words = Arrays.asList("apple", "banana", "cherry");// 計算總長度 int totalLength = words.stream().mapToInt(String::length).sum(); // 結果: 5 + 6 + 6 = 17// 檢查是否所有單詞長度大于 3 boolean allLong = words.stream().allMatch(w -> w.length() > 3); // true
三、并行流(Parallel Stream)
通過
parallelStream()
或stream().parallel()
創建并行流,利用多線程加速處理(適用于大數據量)。List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers.parallelStream().mapToInt(Integer::intValue).sum();
注意:并行流的線程安全問題,避免在流操作中修改共享狀態。
四、Collectors 工具類
Collectors
提供了豐富的收集器,用于將流結果轉換為集合、Map 或進行分組統計。1. 集合收集
List<String> names = people.stream().map(Person::getName).collect(Collectors.toList());
2. 分組統計
Map<Integer, List<Person>> ageGroups = people.stream().collect(Collectors.groupingBy(Person::getAge));
3. 字符串連接
String joined = people.stream().map(Person::getName).collect(Collectors.joining(", ", "[", "]")); // 結果: "[Alice, Bob, Charlie]"
五、應用實例
1. 篩選與映射
class Product {private String name;private double price;private Category category;// 構造方法、getter/setter 略 }enum Category { FOOD, ELECTRONICS, CLOTHING }// 統計電子產品的平均價格 List<Product> products = getProductList(); double avgPrice = products.stream().filter(p -> p.getCategory() == Category.ELECTRONICS).mapToDouble(Product::getPrice).average().orElse(0.0);
2. 分頁處理
List<Product> page2 = products.stream().skip(10) // 跳過前10條.limit(10) // 取10條.collect(Collectors.toList());
六、自我總結
-
Java 流 API 提供了一種高效、優雅的方式處理集合數據,其核心優勢包括:
- 代碼簡潔:鏈式調用減少冗余代碼。
- 內部迭代:自動處理遍歷邏輯,提升可讀性。
- 并行支持:簡化多線程編程,提升大數據處理性能。
- 延遲執行:避免不必要的計算,優化性能。
??七、面試題
題目:
答案;