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