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