常用方式
代碼如下:
public Map<Long, String> getIdNameMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
}
收集成實體本身map
代碼如下:
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}
account -> account是一個返回本身的lambda表達式,其實還可以使用Function接口中的一個默認方法代替,使整個方法更簡潔優雅:
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity()));
}
重復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是有可能重復的。toMap有個重載方法,可以傳入一個合並的函數來解決key沖突問題:
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}
這里只是簡單的使用后者覆蓋前者來解決key重復問題。
指定具體收集的map
toMap還有另一個重載方法,可以指定一個Map的具體實現,來收集數據:
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
}