JDK8的lambda方式List轉(zhuǎn)Map的操作方法
JDK8的lambda方式List轉(zhuǎn)Map
遍歷
public void forEach(Map<Long, String> map) {
map.forEach((k, v) -> {
System.out.println("k=" + k + ",v=" + v);
});
}list轉(zhuǎn)map
代碼如下:
public Map<Long, String> getIdNameMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
}list轉(zhuǎn)成實體本身map
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}account -> account是一個返回本身的lambda表達式,其實還可以使用Function接口中的一個默認方法代替,使整個方法更簡潔優(yōu)雅:
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity()));
}list轉(zhuǎn)map:重復(fù)key處理
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity()));
}這個方法可能報錯(java.lang.IllegalStateException: Duplicate key),因為name是有可能重復(fù)的。toMap有個重載方法,可以傳入一個合并的函數(shù)來解決key沖突問題:
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}這里只是簡單的使用后者覆蓋前者來解決key重復(fù)問題。
舉例:
List<TDeliveryOperation> tDeliveryOperations = tDeliveryOperationMapper.selectList(wrapper1);
Map<Long, TDeliveryOperation> operationMap = tDeliveryOperations.stream()
.collect(Collectors.toMap(
TDeliveryOperation::getOrderId,
Function.identity(),
(key1, key2) -> {
// 如果存在多條記錄 選擇最后更新時間最大的
if (key1.getLastUpdatedAt() != null
&& key2.getLastUpdatedAt() != null
&& key1.getLastUpdatedAt().getTime() >= key2.getLastUpdatedAt().getTime()) {
return key1;
}
return key2;
})
);指定具體收集的map
toMap還有另一個重載方法,可以指定一個Map的具體實現(xiàn),來收集數(shù)據(jù):
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
}到此這篇關(guān)于JDK8的lambda方式List轉(zhuǎn)Map的文章就介紹到這了,更多相關(guān)JDK8 List轉(zhuǎn)Map內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實現(xiàn)解析zip壓縮包并獲取文件內(nèi)容
這篇文章主要為大家詳細介紹了如何利用Java語言實現(xiàn)頁面上傳一個源碼壓縮包,后端將壓縮包解壓,并獲取每個文件中的內(nèi)容,感興趣的可以動手嘗試一下2022-07-07
IntelliJ?IDEA2022.3?springboot?熱部署含靜態(tài)文件(最新推薦)
這篇文章主要介紹了IntelliJ?IDEA2022.3?springboot?熱部署含靜態(tài)文件,本文結(jié)合實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-01-01
mybatis框架order by作為參數(shù)傳入時失效的解決
這篇文章主要介紹了mybatis框架order by作為參數(shù)傳入時失效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06

