当前位置: 首页 > news >正文

list转map常用方法

利用Collectors.toMap收集指定属性

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

收集对象实体本身

- 在开发过程中我们也需要有时候对自己的list中的实体按照其中的一个字段进行分组(比如 id ->List),这时候要设置map的value值是实体本身。

public Map<Long, Account> getIdAccountMap(List<Account> accounts) {return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}

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

重复key的情况

 1.覆盖

    在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));
}

2.分组

groupingBy()
  • 根据一个字段或者属性分组也可以直接用groupingBy方法,很方便。
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());
}
partitioningBy()

可以理解为特殊的groupingBy,key值为true和false,当然此时方法中的参数为一个判断语句(用于判断的函数式接口)

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());
Map.computeIfAbsent()
Map<Integer, List<Person>> personMap = new HashMap<>();  for (Person person : people) {  // Use computeIfAbsent to initialize the list if the key doesn't exist  personMap.computeIfAbsent(person.getId(), k -> new ArrayList<>()).add(person);  }  

http://www.lryc.cn/news/461519.html

相关文章:

  • C++容器适配器的模拟实现-stack、queue、priority_queue
  • fastapi的docs页面是空白解决
  • 浙大数据结构:11-散列4 Hashing - Hard Version
  • pm2 守护http-server
  • 国外电商系统开发-运维系统应用管理
  • 剖析线程池实现原理
  • 【中危】Oracle TNS Listener SID 可以被猜测
  • 三维测量与建模笔记 - 简介
  • Glide 简易教程
  • flutter 使用三方/自家字体
  • 2024台州赛CTFwp
  • 词根plac-和place、please
  • ubuntu下route命令详解
  • 13.java面向对象:面向对象的三大特征
  • 【VUE】Vue中的内置组件
  • 若依框架篇-若依框架搭建具体过程、后端源代码分析、功能详解(权限控制、数据字典、定时任务、代码生成、表单构建、接口测试)
  • 恢复已删除文件的 10 种安卓数据恢复工具
  • Internet Download Manager2025快速下载,新功能解锁!
  • 传感器应用注意事项
  • PayPal美区账号注册指南
  • 《鸟哥的Linux私房菜基础篇》---1 Linux的介绍与如何开启Linux之路
  • 选择排序,插入排序,快速排序的java简单实现
  • 数据库中,超出范围和溢出问题的一些处理方法
  • Re75 读论文:Toolformer: Language Models Can Teach Themselves to Use Tools
  • Android App系统签名
  • Shiro认证(Authentication)
  • Qt和c++面试集合
  • Spark 3.3.x版本中的动态分区裁剪(DPP,Dynamic Partition Pruning)的实现及应用剖析
  • Android 各国语言value文件夹命名规则
  • 深入理解Redis锁与Backoff重试机制在Go中的实现