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

Java根据List集合中的一个字段对集合进行去重

利用HashSet

创建了一个HashSet用于存储唯一的字段值,并创建了一个新的列表uniqueList用于存储去重后的对象。遍历原始列表时,如果字段值未在HashSet中出现过,则将其添加到HashSet和uniqueList中。

		List<Person> originalList = new ArrayList<>();originalList.add(new Person(1, "Alice"));originalList.add(new Person(2, "Bob"));originalList.add(new Person(3, "Alice"));originalList.add(new Person(4, "Charlie"));originalList.add(new Person(5, "Alice"));HashSet<String> uniqueSet = new HashSet<>();List<Person> uniqueList = new ArrayList<>();for (Person person : originalList) {if (uniqueSet.add(person.getName())) {uniqueList.add(person);}}System.out.println(uniqueList);

利用Stream

		List<Person> originalList = new ArrayList<>();originalList.add(new Person(1, "Alice"));originalList.add(new Person(2, "Bob"));originalList.add(new Person(3, "Alice"));originalList.add(new Person(4, "Charlie"));originalList.add(new Person(5, "Alice"));List<Person> uniqueList = originalList.stream().collect(Collectors.toMap(Person::getName, person -> person, (p1, p2) -> p1)).values().stream().collect(Collectors.toList());System.out.println(uniqueList);
		List<Person> originalList = new ArrayList<>();originalList.add(new Person(1, "Alice"));originalList.add(new Person(2, "Bob"));originalList.add(new Person(3, "Alice"));originalList.add(new Person(4, "Charlie"));originalList.add(new Person(5, "Alice"));List<Person> list = new ArrayList<>(originalList);list = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));System.out.println(uniqueList);
http://www.lryc.cn/news/134944.html

相关文章:

  • (AtCoder Beginner Contest 315)
  • API 接口选择那个?RESTful、GraphQL、gRPC、WebSocket、Webhook
  • 「Python|音视频处理|环境准备」如何在Windows系统下安装并配置音视频处理工具FFmpeg
  • 软考高级架构师下篇-12层次式架构设计理论与实践
  • 234. 回文链表
  • LInux之例行工作
  • C++,从“hello world“开始
  • /root/.ssh/config line 2: Bad protocol 2 host key algorithms ‘+ssh-rsa‘.
  • mac m1上系统内录内部声音的方法/无需安装Blackhole
  • 数字人学习目录
  • PHP 房产网站系统Dreamweaver开发mysql数据库web结构php编程计算机网页项目
  • 0基础入门代码审计-2 Fortify初探
  • qiiuzhiji4
  • 构建 NodeJS 影院微服务并使用 docker 部署【01/4】
  • 变频器和plc之间无线MODBUS通讯
  • 【云原生】3分钟快速在Kubernetes1.25部署Prometheus2.42+Grafana9.5.1+Alertmanager0.25
  • Redis中常见的缓存穿透、缓存击穿、缓存雪崩、缓存预热解决方案
  • 第二章-自动驾驶卡车-自动驾驶卡车前装量产的要求
  • Midjourney API 申请及使用
  • mysql mysql 容器 忽略大小写配置
  • 第58步 深度学习图像识别:Transformer可视化(Pytorch)
  • angular实现全局组件
  • Spring编程模型(范式)
  • Golang GORM 单表删除
  • Windows 下 MySQL 源码学习环境搭建步骤【建议收藏】
  • redis总复习
  • [LeetCode - Python]844. 比较;含退格的字符串(Easy);415. 字符串相加(Easy)
  • 机器学习深度学习——NLP实战(自然语言推断——注意力机制实现)
  • mac垃圾清理软件有哪些
  • 8.18 校招 内推 面经