1. 程式人生 > 其它 >使用java8將list轉為map(轉)

使用java8將list轉為map(轉)

常用方式

程式碼如下:

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<Long, List<ActivityUserMissionDO>> map = activityUserMissionDos.stream().collect(Collectors.groupingBy(ActivityUserMissionDO::getParentModuleId));

指定具體收集的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));
}



轉自:https://zacard.net/2016/03/17/java8-list-to-map/