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使用的好文推荐:

相关推荐
睡不醒的kun13 小时前
leetcode算法刷题的第三十二天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
_OP_CHEN15 小时前
数据结构(C语言篇):(十二)实现顺序结构二叉树——堆
c语言·数据结构·算法·二叉树·学习笔记··顺序结构二叉树
cellurw18 小时前
EDID 数据结构解析与编辑工具:校验和计算、厂商/设备名编解码、物理地址读写、颜色与时序信息提取
数据结构
Pluchon18 小时前
硅基计划3.0 Map类&Set类
java·开发语言·数据结构·算法·哈希算法·散列表
❀搜不到19 小时前
查询 conda + pip 装的包
windows·conda·pip
重生之我是Java开发战士19 小时前
【数据结构】Java集合框架:List与ArrayList
java·数据结构·list
爱干饭的boy19 小时前
手写Spring底层机制的实现【初始化IOC容器+依赖注入+BeanPostProcesson机制+AOP】
java·数据结构·后端·算法·spring
字符搬运工-蓝天20 小时前
Win7环境中离线安装Visual Studio 2017的相关问题
ide·windows·visual studio
倔强的石头10620 小时前
Windows系统下KingbaseES数据库保姆级安装教程(附常见问题解决)
数据库·windows
躲在云朵里`20 小时前
Redis深度解析:核心数据结构、线程模型与高频面试题
数据结构·数据库·redis