Java8中list转map方法总结

背景

  • 在最近的工作开发之中,慢慢习惯了很多Java8中的Stream的用法,很方便而且也可以并行的去执行这个流,这边去写一下昨天遇到的一个list转map的场景。

list转map在Java8中stream的应用

常用方式

1.利用Collectors.toMap方法进行转换

auto 复制代码
public Map<Long, String> getIdNameMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
}123

其中第一个参数就是可以,第二个参数就是value的值。

2.收集对象实体本身

  • 在开发过程中我们也需要有时候对自己的list中的实体按照其中的一个字段进行分组(比如 id ->List),这时候要设置map的value值是实体本身。
auto 复制代码
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}123

account -> account是一个返回本身的lambda表达式,其实还可以使用Function接口中的一个默认方法 Function.identity(),这个方法返回自身对象,更加简洁

  1. 重复key的情况。
    • 在list转为map时,作为key的值有可能重复,这时候流的处理会抛出个异常:Java.lang.IllegalStateException:Duplicate key。这时候就要在toMap方法中指定当key冲突时key的选择。(这里是选择第二个key覆盖第一个key)
coffeescript 复制代码
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}123
  1. 用groupingBy 或者 partitioningBy进行分组
    • 根据一个字段或者属性分组也可以直接用groupingBy方法,很方便。
auto 复制代码
Map<Integer, List<Person>> personGroups = Stream.generate(new PersonSupplier()).
 limit(100).
 collect(Collectors.groupingBy(Person::getAge));
Iterator it = personGroups.entrySet().iterator();
while (it.hasNext()) {
 Map.Entry<Integer, List<Person>> persons = (Map.Entry) it.next();
 System.out.println("Age " + persons.getKey() + " = " + persons.getValue().size());
}12345678
  • partitioningBy可以理解为特殊的groupingBy,key值为true和false,当然此时方法中的参数为一个判断语句(用于判断的函数式接口)
auto 复制代码
Map<Boolean, List<Person>> children = Stream.generate(new PersonSupplier()).
 limit(100).
 collect(Collectors.partitioningBy(p -> p.getAge() < 18));
System.out.println("Children number: " + children.get(true).size());
System.out.println("Adult number: " + children.get(false).size());12345

关于stream使用的好文推荐:

相关推荐
苏宸啊5 小时前
链式二叉树基操代码实现&OJ题目
数据结构
风筝在晴天搁浅5 小时前
hot100 25.K个一组翻转链表
数据结构·链表
小十一再加一5 小时前
【初阶数据结构】栈和队列
数据结构
长安er6 小时前
LeetCode136/169/75/31/287 算法技巧题核心笔记
数据结构·算法·leetcode·链表·双指针
_w_z_j_7 小时前
最小栈(栈)
数据结构
fufu03117 小时前
Linux环境下的C语言编程(四十八)
数据结构·算法·排序算法
驱动开发0078 小时前
Windows_Hello_Configuration_Analysis Windows Hello 配置过程分析 setup包分析
windows·驱动开发·云计算·计算机外设·usb重定向
weixin_439706258 小时前
JAVA版日语50音训练(读音强化记忆)
windows
阿蒙Amon8 小时前
C#每日面试题-简述C#访问修饰符
windows·microsoft·c#
思成Codes9 小时前
数据结构:基础线段树——线段树系列(提供模板)
数据结构·算法