Java Stream所有方法實例詳解
一、Stream 創(chuàng)建方法
| 方法 | 說明 | 示例 |
|---|---|---|
stream() | 從集合創(chuàng)建順序流 | list.stream() |
parallelStream() | 創(chuàng)建并行流 | list.parallelStream() |
Stream.of() | 由一組元素創(chuàng)建流 | Stream.of(1, 2, 3) |
Arrays.stream() | 由數(shù)組創(chuàng)建流 | Arrays.stream(arr) |
Stream.iterate() | 生成無限流 | Stream.iterate(0, n -> n+2).limit(5) |
Stream.generate() | 生成無限流 | Stream.generate(Math::random).limit(5) |
二、Stream 中間操作(Intermediate Operations)
這些方法返回新的 Stream,允許鏈?zhǔn)秸{(diào)用。
| 方法 | 說明 | 示例 |
|---|---|---|
filter(Predicate) | 過濾元素 | stream.filter(x -> x > 5) |
map(Function) | 元素映射 | stream.map(x -> x * 2) |
flatMap(Function) | 展開嵌套流 | stream.flatMap(list -> list.stream()) |
distinct() | 去重 | stream.distinct() |
sorted() / sorted(Comparator) | 排序 | stream.sorted() / stream.sorted(Comparator.reverseOrder()) |
peek(Consumer) | 元素遍歷但不終止流 | stream.peek(System.out::println) |
limit(long n) | 截取前 n 個元素 | stream.limit(3) |
skip(long n) | 跳過前 n 個元素 | stream.skip(2) |
三、Stream 終止操作(Terminal Operations)
這些方法會產(chǎn)生結(jié)果或副作用,流被“消費”后不可再用。
| 方法 | 說明 | 示例 |
|---|---|---|
forEach(Consumer) | 遍歷元素 | stream.forEach(System.out::println) |
collect(Collector) | 收集結(jié)果 | stream.collect(Collectors.toList()) |
toArray() | 轉(zhuǎn)數(shù)組 | stream.toArray() |
reduce(BinaryOperator) | 規(guī)約(聚合) | stream.reduce((a, b) -> a + b) |
count() | 計數(shù) | stream.count() |
anyMatch(Predicate) | 是否有任意元素匹配 | stream.anyMatch(x -> x > 5) |
allMatch(Predicate) | 是否所有元素都匹配 | stream.allMatch(x -> x > 5) |
noneMatch(Predicate) | 是否沒有元素匹配 | stream.noneMatch(x -> x > 5) |
findFirst() | 查找第一個元素 | stream.findFirst() |
findAny() | 查找任意元素 | stream.findAny() |
min(Comparator) | 最小值 | stream.min(Comparator.naturalOrder()) |
max(Comparator) | 最大值 | stream.max(Comparator.naturalOrder()) |
四、常用 Collector 收集器
| 方法 | 說明 | 示例 |
|---|---|---|
Collectors.toList() | 轉(zhuǎn) List | stream.collect(Collectors.toList()) |
Collectors.toSet() | 轉(zhuǎn) Set | stream.collect(Collectors.toSet()) |
Collectors.toMap() | 轉(zhuǎn) Map | stream.collect(Collectors.toMap(x -> x, x -> x*2)) |
Collectors.joining() | 字符串拼接 | stream.collect(Collectors.joining(",")) |
Collectors.groupingBy() | 分組 | stream.collect(Collectors.groupingBy(x -> x%2)) |
Collectors.partitioningBy() | 分區(qū) | stream.collect(Collectors.partitioningBy(x -> x > 5)) |
Collectors.counting() | 計數(shù) | stream.collect(Collectors.counting()) |
Collectors.summingInt() | 求和 | stream.collect(Collectors.summingInt(x -> x)) |
Collectors.averagingInt() | 平均值 | stream.collect(Collectors.averagingInt(x -> x)) |
Collectors.maxBy() | 最大值 | stream.collect(Collectors.maxBy(Comparator.naturalOrder())) |
Collectors.minBy() | 最小值 | stream.collect(Collectors.minBy(Comparator.naturalOrder())) |
五、示例代碼
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
// 過濾、映射、收集
List<Integer> result = list.stream()
.filter(x -> x > 3)
.map(x -> x * 2)
.collect(Collectors.toList()); // [8, 10, 12]
// 分組
Map<Boolean, List<Integer>> partitioned = list.stream()
.collect(Collectors.partitioningBy(x -> x % 2 == 0));
// 計數(shù)
long count = list.stream().filter(x -> x > 3).count();
// 求和
int sum = list.stream().reduce(0, Integer::sum);六、補(bǔ)充說明
- 中間操作是惰性求值,只有終止操作執(zhí)行時才會遍歷數(shù)據(jù)。
- Stream 不能被復(fù)用,終止操作后需重新創(chuàng)建流。
- 并行流(parallelStream)適用于大數(shù)據(jù)量,但需注意線程安全和性能。
七、Stream 高級用法
1. 多級分組
Map<String, Map<Integer, List<User>>> multiGroup = users.stream()
.collect(Collectors.groupingBy(
User::getCity,
Collectors.groupingBy(User::getAge)
));說明:先按城市分組,再按年齡分組,結(jié)果是嵌套的 Map。
2. 分區(qū)與分組的區(qū)別
- 分區(qū):只有兩組(true/false),適合布爾條件。
- 分組:可以有多個分組鍵。
Map<Boolean, List<Integer>> partition = list.stream()
.collect(Collectors.partitioningBy(x -> x > 3));3. 自定義收集器
可以通過Collector.of自定義收集邏輯:
Collector<Integer, ?, Set<Integer>> toCustomSet = Collector.of(
HashSet::new,
Set::add,
(left, right) -> { left.addAll(right); return left; }
);
Set<Integer> set = list.stream().collect(toCustomSet);4. 并行流
list.parallelStream()
.filter(x -> x > 3)
.forEach(System.out::println);注意:并行流適合 CPU 密集型任務(wù),IO 密集型需謹(jǐn)慎;操作需線程安全。
5. Optional 結(jié)合 Stream
Optional<Integer> first = list.stream().filter(x -> x > 3).findFirst(); first.ifPresent(System.out::println);
八、常見陷阱與注意點
- 流只能用一次
- 流操作后已關(guān)閉,不能再操作,否則拋異常。
- 修改集合元素
- 不建議在流操作中直接修改原集合元素,推薦返回新集合。
- 空指針問題
- Stream 操作前應(yīng)確保集合非 null,推薦使用
Optional.ofNullable(list).orElse(Collections.emptyList()).stream()。
- Stream 操作前應(yīng)確保集合非 null,推薦使用
- 性能問題
distinct()、sorted()等操作會增加性能消耗。- 并行流適合數(shù)據(jù)量大且操作無副作用的場景。
九、部分方法源碼簡析
1. filter
default Stream<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
return new ReferencePipeline.StatelessOp<>(this, StreamShape.REFERENCE, StreamOpFlag.NOT_SORTED) {
@Override
Sink<T> opWrapSink(int flags, Sink<T> sink) {
return new Sink.ChainedReference<T, T>(sink) {
@Override
public void accept(T t) {
if (predicate.test(t)) downstream.accept(t);
}
};
}
};
}說明:filter 實際上是對每個元素執(zhí)行 Predicate 判斷,符合條件則傳遞到下游。
2. map
default <R> Stream<R> map(Function<? super T, ? extends R> mapper) {
Objects.requireNonNull(mapper);
return new ReferencePipeline.StatelessOp<>(this, StreamShape.REFERENCE, StreamOpFlag.NOT_SORTED) {
@Override
Sink<T> opWrapSink(int flags, Sink<R> sink) {
return new Sink.ChainedReference<T, R>(sink) {
@Override
public void accept(T t) {
downstream.accept(mapper.apply(t));
}
};
}
};
}說明:map 通過 Function 映射每個元素,返回新的流。
十、典型業(yè)務(wù)場景舉例
1. 數(shù)據(jù)去重并排序
List<String> sorted = list.stream()
.distinct()
.sorted()
.collect(Collectors.toList());2. 統(tǒng)計分組后的最大值
Map<String, Optional<User>> maxAgeByCity = users.stream()
.collect(Collectors.groupingBy(
User::getCity,
Collectors.maxBy(Comparator.comparingInt(User::getAge))
));3. 多字段分組統(tǒng)計
Map<String, Map<Integer, Long>> groupCount = users.stream()
.collect(Collectors.groupingBy(
User::getCity,
Collectors.groupingBy(User::getAge, Collectors.counting())
));4. 批量字段提取
List<String> names = users.stream()
.map(User::getName)
.collect(Collectors.toList());5. Stream 處理 Map
Map<String, Integer> map = ...;
List<String> keys = map.entrySet().stream()
.filter(e -> e.getValue() > 5)
.map(Map.Entry::getKey)
.collect(Collectors.toList());十一、Stream API 性能建議
- 盡量減少中間操作鏈長度,必要時合并操作。
- 大數(shù)據(jù)量推薦并行流,但需測試線程安全和實際效率。
- 優(yōu)先使用基本類型流(IntStream、LongStream、DoubleStream)可減少裝箱/拆箱開銷。
- 避免在流中寫復(fù)雜邏輯,建議拆分為多個方法提高可讀性。
十二、Stream 相關(guān)擴(kuò)展
- IntStream/LongStream/DoubleStream:針對基本類型的流,效率更高。
- Collectors.toConcurrentMap:并發(fā)收集器,適合并行流。
- Collectors.mapping:在分組或分區(qū)時對元素做映射。
- Collectors.reducing:自定義規(guī)約操作。
十三、基本類型流詳解
Java 提供了三種基本類型流,分別是 IntStream、LongStream 和 DoubleStream,它們避免了自動裝箱/拆箱,提高了性能。
創(chuàng)建方式
IntStream intStream = IntStream.of(1, 2, 3, 4); LongStream longStream = LongStream.range(1, 10); // [1,9] DoubleStream doubleStream = DoubleStream.generate(Math::random).limit(5);
常用方法
| 方法 | 說明 | 示例 |
|---|---|---|
sum() | 求和 | intStream.sum() |
average() | 平均值 | intStream.average().getAsDouble() |
max() / min() | 最大/最小值 | intStream.max().getAsInt() |
boxed() | 轉(zhuǎn)換為對象流 | intStream.boxed() |
mapToObj() | 基本類型流轉(zhuǎn)對象流 | intStream.mapToObj(String::valueOf) |
十四、流的收集與轉(zhuǎn)換技巧
1. 轉(zhuǎn)換為 Map,處理 key 重復(fù)
// value 相加
Map<String, Integer> map = list.stream()
.collect(Collectors.toMap(
User::getName,
User::getScore,
Integer::sum // 合并函數(shù)
));2. 收集為不可變集合
List<String> unmodifiableList = list.stream()
.collect(Collectors.collectingAndThen(
Collectors.toList(),
Collections::unmodifiableList
));3. 多字段分組
Map<String, Map<Integer, List<User>>> group = users.stream()
.collect(Collectors.groupingBy(
User::getCity,
Collectors.groupingBy(User::getAge)
));十五、Stream 與并發(fā)/線程安全
- 并行流:
parallelStream()會自動分片并行處理,適合無狀態(tài)、無副作用的操作。 - 線程安全收集:使用
Collectors.toConcurrentMap、ConcurrentHashMap等。
ConcurrentMap<String, Integer> concurrentMap = list.parallelStream()
.collect(Collectors.toConcurrentMap(User::getName, User::getScore));十六、Stream 排序技巧
1. 單字段排序
list.stream()
.sorted(Comparator.comparing(User::getAge))
.collect(Collectors.toList());2. 多字段排序
list.stream()
.sorted(Comparator.comparing(User::getAge)
.thenComparing(User::getName))
.collect(Collectors.toList());3. 逆序排序
list.stream()
.sorted(Comparator.comparing(User::getAge).reversed())
.collect(Collectors.toList());十七、Stream 實用代碼片段
1. 找出重復(fù)元素
Set<Integer> seen = new HashSet<>();
Set<Integer> duplicates = list.stream()
.filter(n -> !seen.add(n))
.collect(Collectors.toSet());2. 分頁功能
int page = 2, size = 5;
List<Integer> pageList = list.stream()
.skip((page - 1) * size)
.limit(size)
.collect(Collectors.toList());3. 按條件統(tǒng)計數(shù)量
long count = list.stream().filter(x -> x > 10).count();
4. 合并兩個 List 并去重
List<Integer> merged = Stream.concat(list1.stream(), list2.stream())
.distinct()
.collect(Collectors.toList());十八、常見問題與解決方案
1. Stream 只用一次
Stream<String> s = list.stream(); s.forEach(System.out::println); // s.forEach(...) // 拋異常,不可再用
解決:重新創(chuàng)建流。
2. NullPointerException
集合為 null 時不能直接調(diào)用 stream()。
List<String> safeList = Optional.ofNullable(list)
.orElse(Collections.emptyList());
safeList.stream()...3. 性能瓶頸
- 避免在流操作中寫復(fù)雜邏輯,拆分方法。
- 并行流適合數(shù)據(jù)量大且操作無副作用,需實際測試。
十九、Collectors 的擴(kuò)展用法
1. mapping
分組后對分組內(nèi)元素做映射:
Map<String, List<String>> nameGroup = users.stream()
.collect(Collectors.groupingBy(
User::getCity,
Collectors.mapping(User::getName, Collectors.toList())
));2. reducing
自定義聚合:
int totalScore = users.stream()
.collect(Collectors.reducing(0, User::getScore, Integer::sum));二十、Stream 處理嵌套集合
List<List<Integer>> nested = Arrays.asList(
Arrays.asList(1,2),
Arrays.asList(3,4)
);
List<Integer> flat = nested.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());二十一、Stream API 新增方法(Java 9+)
如果你用的是 Java 9 及以上,還可以用:
takeWhile(Predicate):從頭開始,遇到不滿足條件就停止。dropWhile(Predicate):從頭開始,遇到不滿足條件后開始收集。Stream.ofNullable(obj):對象為 null 返回空流,否則返回單元素流。
Stream.ofNullable(null).count(); // 0
Stream.ofNullable("abc").count(); // 1二十二、Stream 與 Lambda 表達(dá)式最佳實踐
- 保持流操作簡潔,避免嵌套 lambda 過多。
- 推薦將復(fù)雜邏輯提取為方法引用或單獨方法。
- 用注釋說明復(fù)雜的流鏈。
總結(jié)
Java Stream 提供了豐富的 API,適合處理集合的各種操作,包括過濾、映射、分組、聚合、排序、去重等。掌握 Stream 可以極大提升 Java 代碼的簡潔性和表現(xiàn)力。
到此這篇關(guān)于Java Stream所有方法實例詳解的文章就介紹到這了,更多相關(guān)Java Stream所有方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring security中的csrf防御原理(跨域請求偽造)
這篇文章主要介紹了spring security中的csrf防御機(jī)制原理解析(跨域請求偽造),本文通過實例代碼詳解的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12
java實現(xiàn)DWG文件轉(zhuǎn)圖片的示例代碼
在Java中將DWG文件轉(zhuǎn)換為圖片是一個常見的需求,下面將詳細(xì)介紹如何使用Java將DWG文件轉(zhuǎn)換為圖片,并探討幾個流行的解決方案,大家可以根據(jù)需要進(jìn)行選擇2025-10-10
eclipse中沒有SERVER的解決辦法(超詳細(xì))
使用eclipse進(jìn)行tomcat配置時,經(jīng)常會發(fā)現(xiàn)一個重要的問題就是打開eclipse之后沒有了server選項,所以本給大家詳細(xì)介紹了eclipse中沒有SERVER的解決辦法,文中有詳細(xì)的圖文講解,需要的朋友可以參考下2023-12-12
spring-security關(guān)閉登錄框的實現(xiàn)示例
這篇文章主要介紹了spring-security關(guān)閉登錄框的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
完美解決Spring Boot前端的Access-Control-Allow-Origin跨域問題
這篇文章主要介紹了完美解決Spring Boot前端的Access-Control-Allow-Origin跨域問題,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05
java easyPOI實現(xiàn)導(dǎo)出一對多數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了java如何利用easyPOI實現(xiàn)導(dǎo)出一對多數(shù)據(jù),并且可以設(shè)置邊框、字體和字體大小,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12

