欢迎光临散文网 会员登陆 & 注册

java8 list 转Map

2022-05-13 11:08 作者:wulizhao1  | 我要投稿

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


java8 list 转Map的评论 (共 条)

分享到微博请遵守国家法律