JAVA实体类集合该如何去重?
JAVA实体类集合该如何去重?
最近在工作中经常遇到需要去重的需求,所以特意系统的来梳理一下
有目录,不迷路
- JAVA实体类集合该如何去重?
- 单元素去重
- 方法一:利用Set去重
- 方法二:利用java 8的stream写法,方便优雅快捷高效
- 实体类对象去重
- 单属性去重
- 方法一:利用map去重
- 方法二:利用map去重,java 8语法
- 方法三:利用Set去重
- 方法四: 利用Set去重,java 8写法
- 方法五:定义过滤器
- 补充
- 多属性去重
- 方法一:利用map根据姓名、年龄去重
- 方法二:利用map根据姓名、年龄去重,java 8写法
- 方法三:利用Set根据姓名、年龄去重,java 8写法
- 重写equals()和hashCode()方法
- 方法四:利用java 8 的distinct(),最推荐
- 方法五:通过contains()方法来调用equals()方法来对比
- 方法六:重写方法后,通过Set去重
单元素去重
方法一:利用Set去重
public static void main(String[] args) {// 生成含重复元素的集合并打印List<Integer> list = new ArrayList<>();list.add(1);list.add(2);list.add(2);list.add(3);System.out.println("去重前:" + list);// 利用HashSet去重后并打印HashSet<Integer> hashSet = new HashSet<>(list);list.clear();list.addAll(hashSet);System.out.println("去重后:" + list);}
执行:

方法二:利用java 8的stream写法,方便优雅快捷高效
public static void main(String[] args) {// 生成含重复元素的集合并打印List<Integer> list = new ArrayList<>();list.add(2);list.add(3);list.add(3);list.add(4);System.out.println("去重前:" + list);// 利用java 8的stream写法list = list.stream().distinct().collect(Collectors.toList());System.out.println("去重后:" + list);}
执行:

实体类对象去重
先新建实体类:
/*** @Author: guqueyue* @Description: 学生类* @Date: 2023/12/12**/
public class Student {/** 姓名 */private String name;/** 年龄 */private Integer age;public Student() {}public Student(String name, Integer age) {this.name = name;this.age = age;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}
}
单属性去重
方法一:利用map去重
public static void main(String[] args) {// 生成学生集合List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三", 18));studentList.add(new Student("张三", 19));studentList.add(new Student("张三", 22));studentList.add(new Student("李四", 18));System.out.println("去重前: " + studentList);// 利用map根据姓名去重Map<String, Student> map = new HashMap<>();for (Student student : studentList) {map.put(student.getName(), student);}studentList = new ArrayList<>(map.values());System.out.println("去重后: " + studentList);}
执行得:

方法二:利用map去重,java 8语法
比方法一代码看似简洁了,但实际上好似更加复杂了
public static void main(String[] args) {// 生成学生集合List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三", 18));studentList.add(new Student("张三", 19));studentList.add(new Student("张三", 18));studentList.add(new Student("李四", 18));System.out.println("去重前: " + studentList);// 利用map根据姓名去重,java 8语法studentList = studentList.stream().collect(Collectors.toMap(student -> student.getName(), Function.identity(), (o, n) -> n)).values().stream().collect(Collectors.toList());System.out.println("去重后: " + studentList);}
执行:

方法三:利用Set去重
public static void main(String[] args) {// 生成学生集合List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三", 18));studentList.add(new Student("张三", 19));studentList.add(new Student("张三", 18));studentList.add(new Student("李四", 18));System.out.println("去重前: " + studentList);// 利用Set去重
// Set<Student> set = new TreeSet<>(((o1, o2) -> o1.getName().compareTo(o2.getName())));Set<Student> set = new TreeSet<>((Comparator.comparing(Student::getName)));set.addAll(studentList);studentList.clear();studentList = new ArrayList<>(set);System.out.println("去重后: " + studentList);}
执行:

方法四: 利用Set去重,java 8写法
public static void main(String[] args) {// 生成学生集合List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三", 18));studentList.add(new Student("张三", 19));studentList.add(new Student("张三", 18));studentList.add(new Student("李四", 18));System.out.println("去重前: " + studentList);// 利用Set去重,java 8写法studentList = studentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))),ArrayList::new));System.out.println("去重后: " + studentList);}
执行:

方法五:定义过滤器
public static void main(String[] args) {// 生成学生集合List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三", 18));studentList.add(new Student("张三", 19));studentList.add(new Student("张三", 18));studentList.add(new Student("李四", 18));System.out.println("去重前: " + studentList);// 定义过滤器studentList = studentList.stream().filter(distinctKey(Student::getName)).collect(Collectors.toList());System.out.println("去重后: " + studentList);}/*** @Description 自定义过滤器* @Param [keyExtractor]* @return java.util.function.Predicate<T>**/public static <T> Predicate<T> distinctKey(Function<? super T, Object> keyExtractor) {Map<Object, Boolean> map = new ConcurrentHashMap<>();return o -> map.putIfAbsent(keyExtractor.apply(o), Boolean.TRUE) == null;}
执行:

补充
补充一点,如何提取去重后的单元素集合:
public static void main(String[] args) {// 生成学生集合List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三", 18));studentList.add(new Student("张三", 19));studentList.add(new Student("张三", 18));studentList.add(new Student("李四", 18));System.out.println("去重前: " + studentList);// 提取去重后的姓名List<String> nameList = studentList.stream().map(Student::getName).distinct().collect(Collectors.toList());System.out.println("去重后: " + nameList);}
执行:

多属性去重
方法一:利用map根据姓名、年龄去重
public static void main(String[] args) {// 生成学生集合List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三", 18));studentList.add(new Student("张三", 19));studentList.add(new Student("张三", 18));studentList.add(new Student("李四", 18));System.out.println("去重前: " + studentList);// 利用map根据姓名、年龄去重Map<String, Student> map = new HashMap<>();for (Student student : studentList) {map.put(student.getName() + "_" + student.getAge(), student);}studentList = new ArrayList<>(map.values());System.out.println("去重后: " + studentList);}
执行:

方法二:利用map根据姓名、年龄去重,java 8写法
public static void main(String[] args) {// 生成学生集合List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三", 18));studentList.add(new Student("张三", 19));studentList.add(new Student("张三", 18));studentList.add(new Student("李四", 18));System.out.println("去重前: " + studentList);// 利用map根据姓名、年龄去重,java 8写法studentList = studentList.stream().collect(Collectors.toMap(s -> s.getName() + "_" + s.getAge(), Function.identity(), (o, n) -> n)).values().stream().collect(Collectors.toList());System.out.println("去重后: " + studentList);}
执行:

方法三:利用Set根据姓名、年龄去重,java 8写法
public static void main(String[] args) {// 生成学生集合List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三", 18));studentList.add(new Student("张三", 19));studentList.add(new Student("张三", 18));studentList.add(new Student("李四", 18));System.out.println("去重前: " + studentList);// 利用Set根据姓名、年龄去重,java 8写法studentList = studentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + "_" + o.getAge()))), ArrayList::new));System.out.println("去重后: " + studentList);}
执行:

重写equals()和hashCode()方法
下面的几种方法首先需要在实体类中重写equals()和hashCode()方法
@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Student student = (Student) o;return Objects.equals(name, student.name) && Objects.equals(age, student.age);}@Overridepublic int hashCode() {return Objects.hash(name, age);}
方法四:利用java 8 的distinct(),最推荐
public static void main(String[] args) {// 生成学生集合List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三", 18));studentList.add(new Student("张三", 19));studentList.add(new Student("张三", 18));studentList.add(new Student("李四", 18));System.out.println("去重前: " + studentList);// 利用java 8 的distinct(),根据姓名和年龄去重studentList = studentList.stream().distinct().collect(Collectors.toList());System.out.println("去重后: " + studentList);}
执行:

方法五:通过contains()方法来调用equals()方法来对比
public static void main(String[] args) {// 生成学生集合List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三", 18));studentList.add(new Student("张三", 19));studentList.add(new Student("张三", 18));studentList.add(new Student("李四", 18));System.out.println("去重前: " + studentList);// 通过contains()方法来调用equals()方法来对比,根据姓名和年龄去重List<Student> newStudentList = new ArrayList<>();for (Student student : studentList) {if (!newStudentList.contains(student)) {newStudentList.add(student);}}System.out.println("去重后: " + newStudentList);}
执行:

方法六:重写方法后,通过Set去重
public static void main(String[] args) {// 生成学生集合List<Student> studentList = new ArrayList<>();studentList.add(new Student("张三", 18));studentList.add(new Student("张三", 19));studentList.add(new Student("张三", 18));studentList.add(new Student("李四", 18));System.out.println("去重前: " + studentList);// 通过Set,根据姓名和年龄去重Set<Student> set = new HashSet<>(studentList);studentList.clear();studentList.addAll(set);System.out.println("去重后: " + studentList);}
执行:

完结撒花!!!

相关文章:
JAVA实体类集合该如何去重?
JAVA实体类集合该如何去重? 最近在工作中经常遇到需要去重的需求,所以特意系统的来梳理一下 有目录,不迷路 JAVA实体类集合该如何去重?单元素去重方法一:利用Set去重方法二:利用java 8的stream写法…...
修改Element UI可清空Input的样式
如图所示,修改Input右侧的清空按钮位置: <el-input class"create-catalog-ipt"placeholder"请输入相关章节标题"v-model"currentCatalogTitle"clearable /> // SCSS环境 ::v-deep {.create-catalog-ipt {input {he…...
Java常用注解
文章目录 第一章、Java注解与元数据1.1)元数据与注解概念介绍1.2)Java注解的作用和使用1.3)注解的分类 第二章、Mybatis框架常用注解2.1)Mybatis注解概览2.2)常用注解MapperScanMapperSelectInsertUpdateDeleteParam结…...
golang实现同步阻塞、同步非阻塞、异步非阻塞IO模型
一、同步阻塞IO模型TCP和HTTP示例 同步阻塞IO符合我们的直觉认知,应用程序从TCP连接接收数据缓冲区接受数据,如果没有数据就等待——此处就是阻塞,如果有数据需要把数据从内核空间读取到用户空间——此处就是同步。 在Go语言中进行同步阻塞IO编程TCP交互,可以使用标准库中…...
java SSM教师工作量管理系统myeclipse开发mysql数据库springMVC模式java编程计算机网页设计
一、源码特点 java SSM 教师工作量管理系统是一套完善的web设计系统(系统采用SSM框架进行设计开发,springspringMVCmybatis),对理解JSP java编程开发语言有帮助,系统具有完整的源代码和数据库,系统主要…...
大数据技术之Hive(超级详细)
第1章 Hive入门 1.1 什么是Hive Hive:由Facebook开源用于解决海量结构化日志的数据统计。 Hive是基于Hadoop的一个数据仓库工具,可以将结构化的数据文件映射为一张表,并提供类SQL查询功能。 本质是:将HQL转化成MapReduce程序 …...
NVMe over Fabrics with SPDK with iRDMA总结 - 1
1.0 Introduction简介 NVM Express* (NVMe*) drives are high-speed, low-latency, solid-state drives (SSDs), that connect over the server Peripheral Component Interconnect Express* (PCIe*) bus. NVM Express* (NVMe*) 硬盘是高速、低延迟的固态硬盘 (SSD),通过服…...
【PTA刷题】求链式线性表的倒数第K项(代码+详解)
文章目录 题目代码详解 题目 给定一系列正整数,请设计一个尽可能高效的算法,查找倒数第K个位置上的数字。 输入格式: 输入首先给出一个正整数K,随后是若干非负整数,最后以一个负整数表示结尾(该负数不算在序列内&#…...
VSCode 创建工作区,多文件夹终端切换
VSCode 创建工作区的好处有以下几点: 项目结构清晰:每个工作区都有自己的文件夹结构,可以更好地组织和管理项目文件。版本控制:VSCode 支持多种版本控制系统,如Git,可以在工作区内进行代码的版本管理。插件…...
高阶函数(js的问题)
(1)函数可以作为参数被传递 (2)函数可以作为返回值输出 4-1.函数作为参数传递 Array.prototype.sort方法: var array [10,5,12,3];array.sort();//array:[10,12,3,5]//如代码那样,排序的结果并不是我们想要…...
android-android源码目录
android源码目录 Android.bp art bionic bootable bootstrap.bash build build.sh compatibility cts dalvik developers development device external frameworks: Android 系统的核心框架代码av: 该目录包含与音视频相关的框架和库,如音频解码器、视频编码器、多…...
Json格式化
Json格式化 大家好,我是微赚淘客机器人的小编,也是冬天不穿秋裤,天冷也要风度的程序猿! Json格式化:让数据更亮眼,解密Json的奇妙世界 在现代Web开发中,Json(JavaScript Object N…...
数据可视化设计:让数据故事更有说服力
写在开头 在数字化的时代,数据如同一把锁住的宝剑,等待我们挥舞。然而,唯有通过巧妙运用数据可视化的原则和技术,我们才能真正解锁数据的力量,创造出令人信服的数据故事。本文将深入研究数据可视化设计的奥秘,揭示其中的魔法,让你在数据的海洋中游刃有余,用数据的语言…...
java面试题-Spring事务以及@Transactional注解详解
远离八股文,面试大白话,通俗且易懂 看完后试着用自己的话复述出来。有问题请指出,有需要帮助理解的或者遇到的真实面试题不知道怎么总结的也请评论中写出来,大家一起解决。 java面试题汇总-目录-持续更新中 对于这个面试中高频问到…...
ARM流水灯
.text .global _start _start: LED1 1.RCC时钟使能GPIOE RCC_MP_AHB4ENSETR[4]->1 LDR R0,0x50000a28 LDR R1,[R0] ORR R1,R1,#(0x1<<4) STR R1,[R0] 2.设置PE10为输出模式 GPIOE_MODER[21:20]->01 先清0 LDR R0,0x50006000 LDR R1,[R0] BIC R1,R1,#(0x3<&…...
docker-compose单机容器编排
Dockerfile:先配置好文件,然后build,镜像-------->容器。 docker-conpose 既可以基于dockerfile,也可以基于镜像,一键式拉起镜像和容器。 docker-compose核心就是yml文件,可以定义容器的一切。通过yml配置,直接运行…...
matlab信号分选系统算法-完整算法结构
matlab信号分选系统算法 针对得到的脉冲流PDW进行信号分选,包括重频恒定、重频抖动、重频参差和重频滑变四种脉间调制类型。 这里我们先进行数据的仿真,后续边仿真边分享思路:首先根据信号类型,分别产生重频恒定、重频抖动、重…...
十八)Stable Diffusion使用教程:艺术二维码案例
今天说说怎么样使用SD生成艺术二维码。 我们直接上图。 方式有三种,分别如下: 1)方式一:直接 contronet 的tile模型进行控制 使用QRBTF Classic生成你的二维码。 首先输入网址,选择喜欢的二维码样式(推荐第一种就行): 然后选择相应参数,这里推荐最大的容错率,定…...
【LeetCode每日一题】53. 最大子数组和
https://leetcode.cn/problems/maximum-subarray/description/ 给你一个整数数组 nums ,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 子数组 是数组中的一个连续部分。 方式一:暴力…...
机器学习笔记 什么是协方差矩阵?
一、协方差矩阵 协方差矩阵是一种矩阵,用于表示随机向量中给定的元素对之间的协方差值。协方差矩阵也可以称为色散矩阵或方差-协方差矩阵。这是因为每个元素的方差是沿着矩阵的主对角线表示的。 协方差矩阵始终是方阵。此外,它是半正定且对称的。该矩阵在随机建模和主成分分析…...
HPM6750 CAN FD实战:从波特率配置到高效收发,避坑指南
1. 项目概述:从经典CAN到CAN FD的实战入门作为一名长期在嵌入式领域摸爬滚打的开发者,我深知现场总线技术,尤其是CAN总线,在工业控制、汽车电子等领域的核心地位。随着数据吞吐量需求的激增,经典CAN的1Mbps带宽逐渐捉襟…...
《迈向生产的智能体》开源指南:28个教程助你将AI智能体转化为现实产品!
《迈向生产的智能体》开源指南:涵盖28个生产级教程,助你将AI智能体转化为现实产品!《迈向生产的智能体》是构建可从原型扩展到企业级应用的生成式AI(GenAI)智能体的首选资源,教程涵盖有状态工作流、向量内存…...
终极Windows离线语音识别指南:打造企业级隐私安全的实时字幕系统
终极Windows离线语音识别指南:打造企业级隐私安全的实时字幕系统 【免费下载链接】TMSpeech 腾讯会议摸鱼工具 项目地址: https://gitcode.com/gh_mirrors/tm/TMSpeech 在数字化办公和远程协作日益普及的今天,实时语音转文字技术已成为提升工作效…...
智能路由器项目解析:基于策略路由实现多线路流量智能调度
1. 项目概述:一个“聪明”的路由器能做什么?最近在GitHub上看到一个挺有意思的项目,叫smart-router,作者是c0nSpIc0uS7uRk3r。光看名字,你可能会觉得这又是一个关于家庭网络优化的工具,但点进去仔细研究后&…...
δ - mem:提升大型语言模型内存效率,得分最高可达 1.31 倍!
快速通道可了解 arXiv 成为独立非营利组织的情况,也能直达康奈尔大学官网。同时,还能通过链接进行捐赠,支持 arXiv 的发展。搜索与导航提供了多种搜索途径,可在所有字段(标题、作者、摘要等)进行搜索。还有…...
阴阳师自动化脚本OAS终极指南:轻松解放双手的完整教程
阴阳师自动化脚本OAS终极指南:轻松解放双手的完整教程 【免费下载链接】OnmyojiAutoScript Onmyoji Auto Script | 阴阳师脚本 项目地址: https://gitcode.com/gh_mirrors/on/OnmyojiAutoScript 阴阳师自动化脚本OAS是一款专门为《阴阳师》游戏设计的智能自动…...
MySQL 索引底层 B+ 树原理
聊 MySQL 索引,不讲 B 树,那就是在耍流氓。 大家好,我是乱码字符。今天咱们深入聊聊 MySQL 索引的底层数据结构——B 树。这篇文章能让你彻底搞明白,为什么有时候明明加了索引,查询却还是慢成狗。 先说说为什么要用树结…...
Vim-ai插件深度指南:在Vim中无缝集成AI提升开发效率
1. 项目概述:当Vim遇上AI,一场编辑器生产力的革命如果你和我一样,是个在终端里泡了十多年的老Vim用户,那你一定经历过这样的场景:面对一个复杂的函数重构,手指在键盘上飞舞,:s、%s、宏录制轮番上…...
ComfyUI ControlNet Aux 终极指南:30+种预处理器让AI图像生成更精准
ComfyUI ControlNet Aux 终极指南:30种预处理器让AI图像生成更精准 【免费下载链接】comfyui_controlnet_aux ComfyUIs ControlNet Auxiliary Preprocessors 项目地址: https://gitcode.com/gh_mirrors/co/comfyui_controlnet_aux 想让您的AI图像生成具备真实…...
【c++面向对象编程】第24篇:类型转换运算符:自定义隐式转换与explicit
目录 一、一个自然的想法 二、类型转换运算符的基本语法 写法 使用 三、隐式转换的风险 问题1:意外的不希望发生的转换 问题2:多个转换路径的歧义 问题3:与构造函数隐式转换叠加导致混乱 四、explicit:禁止隐式转换 语法…...
