天天看点

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