Stream將List轉為Map匯總、排序


Stream將List轉換為Map,使用Collectors.toMap方法進行轉換。

背景:User類,類中分別有id,name,age三個屬性。List集合,userList,存儲User對象

 

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));

 進階:https://blog.csdn.net/qq_39629277/article/details/83012548

 

 

======  按照容器狀態排序、cellNo倒序==

 

allCanOutStockList = stockDtotempList.stream()
.filter(stockDto -> rpPickDContainerNoList.contains(stockDto.getContainerNo()))
.sorted(Comparator.comparing(StockDtoTemp::getContainerStatus)
.thenComparing(StockDtoTemp::getCanUseQty)
.thenComparing(StockDtoTemp::getCellNo,Comparator.reverseOrder()))
.collect(Collectors.toList());


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM