天天看點

Java8 lambda list轉map

1、list轉Map<String,String>

public Map<String, String> getIdNameMap(List<Account> accounts) {
    return accounts.parallelStream().collect(Collectors.toMap(Account::getUserId, Account::getUsername));
}
           

2、list轉Map<String,Account>

public Map<String, Account> getIdAccountMap(List<Account> accounts) {
    return accounts.parallelStream().collect(Collectors.toMap(Account::getUserId, account -> account));
}
           

或者這樣寫

public Map<String, Account> getIdAccountMap(List<Account> accounts) {
    return accounts.parallelStream().collect(Collectors.toMap(Account::getUserId, Function.identity()));
}
           

這樣寫會存在key重複的問題,可以這樣寫去解決

public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.parallelStream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}
           

toMap還有另一個重載方法,可以指定一個Map的具體實作,來收集資料:

public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.parallelStream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
}