Stream API的實戰案例
ps:我個人比較偏向於代碼與實踐向結合,所以在一些專業的術語方面也有些粗糙,
以下內容僅按照我個人的理解進行解釋,如有其它更全面更好解釋,請直接在下面進行評論,或私聊我,我將定時去檢查跟正
Stream ApI的前提條件
- 針對對象: 集合
- 後序內容按照這個下述內容進行分析
- 集合 :List uList
- 對象:User[id, nm,age,sign]
- 後序內容按照這個下述內容進行分析
StreamAPI 常用的方法
-
Stream: (個人理解)就是把一個集合轉換成流對象
-
map: 集合的篩選條件,選取當前集合的那些內容
-
filter: 對集合中的內容進行一次條件判斷,常和findFirst() 連用
-
findFirst(): 把集合中進行條件判斷滿足的內容獲取處理,後序可以進一步篩選(map)
-
reduce: BigDecimal 數字的運算
更多待續~
後序添加—list.stream().map(Dto -> Dto.getXXXXVo().getXXX()).reduce(BigDecimal::add).get();
常用的流使用方法
- 把一個List<對象> 從中取出特定的一些內容,返回一個新的list
* 篩選User的id
uList.stream.map(User::User.getId()).collect(Collectors.toList());
或 uList.stream.map(User->User.getId()).collect(Collectors.toList());
- 把一個List<對象> 並按照一定規則選取,返回一個新的list
* 篩選User的age >18的Age集合
uList.stream.filter(U->{return U.getAge()>18 }).collect(Collectors.toList());
- 把一個List<對象> 從中取出特定的一些內容, 並按照一定規則選取,並賦值,返回一個新的list
* 篩選User的標記sign賦值爲true
uList.stream.map(User->{
User.setSign(true);
return User;
}).collect(Collectors.toList());
- 把一個List<對象> 從中取出特定的一些內容, 並按照一定規則選取,並賦值,返回一個Map
1、指定key-value,value是對象中的某個屬性值。
Map<Integer,String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId,User::getName));
2、指定key-value,value是對象本身,User->User 是一個返回本身的lambda表達式
Map<Integer,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User));
3、指定key-value,value是對象本身,Function.identity()是簡潔寫法,也是返回對象本身
Map<Integer,User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
4、指定key-value,value是對象本身,Function.identity()是簡潔寫法,也是返回對象本身,key 衝突的解決辦法,這裏選擇第二個key覆蓋第一個key。
Map<Integer,User> userMap4 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));
————————————————
版權聲明:本內容摘自爲CSDN博主「﹏半生如夢願夢如真て」的原創文章,
遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/lspj201007186/java/article/details/91039052
- 把兩個List<對象>從中取出特定的一些內容, 並按照一定規則選取,
並把第二個集合中的內容賦值給第一個,返回一個新的集合 - 新的集合List listNew
- 新的對象User1[id, nm,age,sign]
uList.stream().map( item -> listNew.stream()
.filter(newList->newList.getUserId().equals(XXX) && ( newList.getSign.equals(true) )
.findFirst() //把滿足filter的集合獲取到
.map(newList-> {
// ....按內容填充...
item.setUser(new User());item.setId(newList.getId()) return item;
})
).collect(Collectors.toList());