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