第一種: 取list中某2個字段作為Map的K,V
public Map<Long, String> getIdNameMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername)); }
第二種:將id和實體Bean做為K,V
public Map<Long, Account> getIdAccountMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account)); }
或者這樣寫:
public Map<Long, Account> getIdAccountMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity())); }
account -> account是一個返回本身的lambda表達式,后面的使用Function接口中的一個默認方法代替,使整個方法更簡潔優雅。
第三種: key存在重復記錄時處理
public Map<String, Account> getNameAccountMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2)); }
如果使用第一種方法會出錯,所以這里只是簡單的使用后者覆蓋前者來解決key重復問題。
第四種: 使用某個具體的Map類來保存,如保存時使用LinkedHashMap
public Map<String, Account> getNameAccountMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new)); }
第五種: List<Object>轉List<String,Map<String, String>>
類似采購訂單 id,對應明細記錄。
public Map<String,List<MCode>> getCodeListMap(){ if(CollectionUtils.isEmpty(codeListMap)){ List<MCode> codeList = this.getCodeList(); Set<String> keySet = codeList.stream().map(code -> code.getCodeKbn()).collect(Collectors.toSet()); Iterator<String> it = keySet.iterator(); while(it.hasNext()) { String key = it.next(); codeListMap.put(key, codeList.stream().filter(code -> code.getCodeKbn().equals(key)).collect(Collectors.toList())); } } return codeListMap; }