??wei_shuo的個人主頁
??wei_shuo的學(xué)習(xí)社區(qū)
??Hello World !
Java 8:Stream API
Java 8 中的 Stream API 是一組用于對集合數(shù)據(jù)進(jìn)行處理的新特性;提供一種以聲明式風(fēng)格對集合進(jìn)行操作的方式,簡化集合的處理,使得代碼更加簡潔、優(yōu)雅,并且能夠更高效地處理數(shù)據(jù);
這種風(fēng)格將要處理的元素集合看作一種流, 流在管道中傳輸, 并且可以在管道的節(jié)點上進(jìn)行處理, 比如篩選, 排序,聚合等;元素流在管道中經(jīng)過中間操作(intermediate operation)的處理,最后由最終操作(terminal operation)得到前面處理的結(jié)果
+--------------------+ +------+ +------+ +---+ +-------+ | stream of elements +-----> |filter+-> |sorted+-> |map+-> |collect| +--------------------+ +------+ +------+ +---+ +-------+
流程轉(zhuǎn)換為 Java 代碼為:
List<Integer> transactionsIds = widgets.stream() .filter(b -> b.getColor() == RED) .sorted((x,y) -> x.getWeight() - y.getWeight()) .mapToInt(Widget::getWeight) .sum();
特性
聲明式編程風(fēng)格:Stream API 提供了類似于 SQL 查詢的聲明式編程方式,通過鏈?zhǔn)秸{(diào)用一系列方法來對數(shù)據(jù)進(jìn)行操作,而不是顯式地編寫循環(huán)或臨時變量。這使得代碼更加簡潔、易讀和易于理解
惰性求值:Stream 是惰性求值的,即只有在終止操作時才會真正執(zhí)行;中間操作(如 filter、map、sorted 等)只是定義了數(shù)據(jù)流的處理步驟,而不會立即執(zhí)行;這樣可以優(yōu)化處理過程,避免不必要的計算,提高性能
函數(shù)式接口支持:Stream API 需要與函數(shù)式接口(Functional Interface)一起使用;函數(shù)式接口是只包含一個抽象方法的接口,Lambda 表達(dá)式可以作為函數(shù)式接口的實例進(jìn)行傳遞;這種支持使得 Stream API 能夠充分發(fā)揮函數(shù)式編程的優(yōu)勢
生成流
Java 8 中, 集合接口有兩個方法來生成流
stream()
:為集合創(chuàng)建串行流
parallelStream()
?:為集合創(chuàng)建并行流
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
strings 列表創(chuàng)建了一個流,通過 stream() 方法將列表轉(zhuǎn)換成了一個流;然后,使用 filter 方法傳遞一個 Lambda 表達(dá)式來篩選(過濾)不滿足條件的元素;在這里,Lambda 表達(dá)式 string -> !string.isEmpty() 檢查字符串是否非空;只有在字符串不為空的情況下,該元素會被保留在流中;最后,使用 collect 方法,結(jié)合 Collectors.toList() 收集器,將符合條件的元素收集到一個新的列表 filtered 中
流式操作
forEach
Stream 提供了新的方法
forEach
來迭代流中的每個數(shù)據(jù):以下代碼片段使用 forEach 輸出10個隨機(jī)數(shù):
ints()
方法用于生成一個無限的隨機(jī)整數(shù)流
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
map
map 方法用于映射每個元素到對應(yīng)的結(jié)果:以下代碼片段使用 map 輸出了元素對應(yīng)的平方數(shù)
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 獲取對應(yīng)的平方數(shù)
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
filter
filter 方法用于通過設(shè)置的條件過濾出元素:以下代碼片段使用 filter 方法過濾出空字符串
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 獲取空字符串的數(shù)量
long count = strings.stream().filter(string -> string.isEmpty()).count();
limit
limit 方法用于獲取指定數(shù)量的流:以下代碼片段使用 limit 方法打印出 10 條數(shù)據(jù)
Random random = new Random();
random.ints().limit(10).forEach(System.out::println);
sorted
sorted 方法用于對流進(jìn)行排序:以下代碼片段使用 sorted 方法對輸出的 10 個隨機(jī)數(shù)進(jìn)行排序
Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);
并行(parallel)程序
parallelStream 是流并行處理程序的代替方法:以下實例我們使用 parallelStream 來輸出空字符串的數(shù)量
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 獲取空字符串的數(shù)量
long count = strings.parallelStream().filter(string -> string.isEmpty()).count();
Collectors
Collectors 類實現(xiàn)了很多歸約操作,例如將流轉(zhuǎn)換成集合和聚合元素:Collectors 可用于返回列表或字符串
List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
System.out.println("篩選列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合并字符串: " + mergedString);
統(tǒng)計
產(chǎn)生統(tǒng)計結(jié)果的收集器;它們主要用于int、double、long等基本類型上,它們可以用來產(chǎn)生類似如下的統(tǒng)計結(jié)果
List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("列表中最大的數(shù) : " + stats.getMax());
System.out.println("列表中最小的數(shù) : " + stats.getMin());
System.out.println("所有數(shù)之和 : " + stats.getSum());
System.out.println("平均數(shù) : " + stats.getAverage());
map 操作
Stream API 中三種常見的 map 操作:
map
、mapToInt
和flatMap
map
:用于將流中的元素映射為另一種類型的流。例如,將一個對象流中的每個對象映射為對象的某個屬性值組成的流mapToInt
:用于將流中的元素映射為IntStream
,即基本類型int
的流。它通常用于將流中的元素映射為整數(shù)值flatMap
:用于將流中的每個元素映射為一個流,然后將這些流連接成一個單一的流。它通常用于扁平化處理嵌套的流結(jié)構(gòu)
案例
systemApplicationTypeRepo.list(new QueryWrapper<SystemApplicationType>().orderByAsc(SystemApplicationTypeCol.ID))
.stream().map(bean -> new ResCommonIdNameCode(bean.getId(), bean.getName(), bean.getName())).collect(Collectors.toList()
systemApplicationTypeRepo.list(...)
:這部分代碼使用了一個名為 systemApplicationTypeRepo 的倉庫(Repository),通過調(diào)用 list 方法來查詢數(shù)據(jù)庫中的數(shù)據(jù);list 方法接受一個查詢條件對象 QueryWrapper 作為參數(shù),用于指定查詢條件new QueryWrapper<SystemApplicationType>().orderByAsc(SystemApplicationTypeCol.ID)
:這是創(chuàng)建一個查詢條件對象的過程;QueryWrapper 是 MyBatis-Plus 提供的用于構(gòu)建查詢條件的工具;orderByAsc(SystemApplicationTypeCol.ID) 表示按照 SystemApplicationType 實體類中 ID 字段的升序進(jìn)行排序。.stream()
:這將查詢結(jié)果轉(zhuǎn)換為一個 Stream 對象,便于后續(xù)的操作.map(bean -> new ResCommonIdNameCode(bean.getId(), bean.getName(), bean.getName()))
:這部分使用 map 操作將查詢結(jié)果的每個 SystemApplicationType 對象映射為 ResCommonIdNameCode 對象;ResCommonIdNameCode 是一個自定義的類,構(gòu)造函數(shù)接受 id、name 和 code 作為參數(shù),用于創(chuàng)建一個新的對象.collect(Collectors.toList())
:最后,使用 collect 方法將 Stream 對象收集為 List,即最終的結(jié)果列表
noticeResponses.stream()
.sorted(Comparator.comparing(SystemNoticeResponse::getReadStatus)
.thenComparing(Comparator.comparing(SystemNoticeResponse::getCreateAt).reversed()))
.collect(Collectors.toList());
.stream()
:將 noticeResponses 列表轉(zhuǎn)換為一個 Stream 對象,使其能夠使用 Stream API 提供的操作
.sorted(...)
:這是一個中間操作,用于對流中的元素進(jìn)行排序;使用 Comparator.comparing(…) 方法創(chuàng)建了一個比較器,用于指定排序的規(guī)則;首先,按照 SystemNoticeResponse 對象的 readStatus 字段進(jìn)行升序排序;.thenComparing(…) 表示如果 readStatus 相同,則按照 createAt 字段進(jìn)行降序排序(使用 reversed() 方法)
.collect(Collectors.toList())
:最后,使用 collect 方法將排序后的 Stream 對象收集為一個新的 List,即排序后的 noticeResponses 列表
?? 結(jié)語:創(chuàng)作不易,如果覺得博主的文章賞心悅目,還請——
點贊
??收藏
??評論
??文章來源:http://www.zghlxwxcb.cn/news/detail-648837.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-648837.html
到了這里,關(guān)于Java 8:Stream API 流式操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!