Java中如何进行List转Map呢?
下文笔者讲述list转Map的方法及示例分享,如下所示
List转Map的实现思路
借助stream中collect Collectors.toMap方法即可将一个List转换为Map例:List转Map
list转map Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId,Function.identity())); //当转换成map时 //出现key相同的情况 //此时如果不指定一个覆盖规则,上面的代码是会报错的 //即转成map时,需使用以下方式 Map<Long, User> maps = userList.stream() .collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2)); //map的值不是对象 //使用对象的某个属性 //可使用以下方式 Map<Long, String> maps = userList.stream() .collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2)); //List 以ID分组 Map<Integer,List> Map<Integer, List> groupBy = appleList.stream() .collect(Collectors.groupingBy(Apple::getId));
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。