java8 list 轉Map
1 public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
? ? return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}
2 重復key的情況
在list轉為map時,作為key的值有可能重復,這時候流的處理會拋出個異常:Java.lang.IllegalStateException:Duplicate key。
這時候就要在toMap方法中指定當key沖突時key的選擇。(這里是選擇第二個key覆蓋第一個key):
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
? ? return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}? ??
3分組
Map<String, List<CompanyInfo>> companyByMonth = companyInfos.stream()
? ? ? ?.collect(Collectors.groupingBy(o -> o.getCreatedTime().toInstant().atZone(ZoneId.systemDefault())
? ? ? ? ? ? ? ?.toLocalDateTime().getYear() + separate +
? ? ? ? ? ? ? ?o.getCreatedTime().toInstant().atZone(ZoneId.systemDefault())
? ? ? ? ? ? ? ? ? ? ? ?.toLocalDateTime().getMonthValue()));