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

    @Override
    public 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()方法

@Override
    public 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);
    }

    @Override
    public 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);
    }

执行:

在这里插入图片描述
完结撒花!!!
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/242099.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

预测性维护对制造企业设备管理的作用

制造企业设备管理和维护对于生产效率和成本控制至关重要。然而&#xff0c;传统的维护方法往往无法准确预测设备故障&#xff0c;导致生产中断和高额维修费用。为了应对这一挑战&#xff0c;越来越多的制造企业开始采用预测性维护技术。 预测性维护是通过传感器数据、机器学习和…

【教3妹学编程-算法题】消除相邻近似相等字符

插&#xff1a; 前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站。 坚持不懈&#xff0c;越努力越幸运&#xff0c;大家一起学习鸭~~~ 3妹&#xff1a;好冷啊&#xff0c; 冻得瑟瑟发抖啦 2…

Python Paramiko库:SSH远程连接与文件传输实战指南

更多资料获取 &#x1f4da; 个人网站&#xff1a;ipengtao.com 在网络管理和系统运维中&#xff0c;SSH&#xff08;Secure Shell&#xff09;是一种广泛用于远程登录和文件传输的协议。Python中的Paramiko库为开发者提供了灵活、强大的SSH客户端和服务器功能。本文将深入探讨…

微服务实战系列之MQ

前言 从今天起&#xff0c;席卷北国的雪&#xff0c;持续了一整天&#xff0c;北京也不例外。这场意外的寒潮&#xff0c;把整个冬天渲染的格外cool。当然你可以在外面打雪仗、堆雪人、拉雪橇&#xff0c;也可以静坐屋内&#xff0c;来一场围炉煮茶的party。此刻&#xff0c;冬…

社会不教,精英不讲,坎儿还得自己过(揭秘人才成长规律)

推荐大家去看看天涯社区的精华帖子&#xff1a;《社会不教&#xff0c;精英不讲&#xff0c;坎儿还得自己过&#xff08;揭秘人才成长规律&#xff09;》 原出处天涯精华帖&#xff1a;《社会不教&#xff0c;精英不讲&#xff0c;坎儿还得自己过&#xff08;揭秘人才成长规律&…

(企业 / 公司项目)微服务项目解决跨域问题:

前后端分离项目中前端出现了跨域的问题 在网关模块配置文件中添加 配置 application.properties # 允许请求来源&#xff08;老版本叫allowedOrigin&#xff09; spring.cloud.gateway.globalcors.cors-configurations.[/**].allowedOriginPatterns* # 允许携带的头信息 spri…

2023.12.12 关于 Java 反射详解

目录 基本概念 定义 用途 反射相关的类 反射基本原理 Class 类中的相关方法 常用获得类相关的方法 常用获得类中属性相关的方法 常用获得类中构造器相关的方法 常用获得类中方法相关的方法 实例理解 反射优缺点 基本概念 定义 Java 的反射&#xff08;reflection&a…

java中的包

1.包的本质分析(原理) 包的本质 实际上就是创建不同的文件夹来保存类文件 2.一个文件中有两个类的i情况 package com.use;import com.xiaoqiang.Dog;public class Test {public static void main(String[] args) {Dog dog new Dog();System.out.println(dog); //com.xiaoqian…

达索系统SOLIDWORKS 2024 Visualize新功能

SOLIDWORKS Visualize&#xff08;原名为 Bunkspeed&#xff09;是一整套独立的软件工具&#xff0c;Visualize模块主要是用于对SOLIDWORKS设计出的产品图进行渲染、做动画&#xff0c;方便用户更好的展示、宣传产品&#xff1b;以最快速、最轻松的方式创建专业的照片级图像、动…

汽车差速器市场分析:预计2029年将达到218亿元

差速器是为了调整左右轮的转速差而装置的。在四轮驱动时&#xff0c;为了驱动四个车轮&#xff0c;必须将所有的车轮连接起来&#xff0c;如果将四个车轮机械连接在一起&#xff0c;汽车在曲线行驶的时候就不能以相同的速度旋转&#xff0c;为了能让汽车曲线行驶旋转速度基本一…

智能优化算法应用:基于生物地理学算法3D无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于生物地理学算法3D无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于生物地理学算法3D无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.生物地理学算法4.实验参数设定5.算法…

2023年12月14日 十二生肖 今日运势

小运播报&#xff1a;2023年12月14日&#xff0c;星期四&#xff0c;农历十一月初二 &#xff08;癸卯年甲子月丙午日&#xff09;&#xff0c;法定工作日。 红榜生肖&#xff1a;羊、狗、虎 需要注意&#xff1a;牛、马、鼠 喜神方位&#xff1a;西南方 财神方位&#xff…

静态SOCKS5的未来发展趋势和新兴应用场景

随着网络技术的不断发展和进步&#xff0c;静态SOCKS5代理也在不断地完善和发展。未来&#xff0c;静态SOCKS5代理将会呈现以下发展趋势和新兴应用场景。 一、发展趋势 安全性更高&#xff1a;随着网络安全问题的日益突出&#xff0c;用户对代理服务器的安全性要求也越来越高…

2-分布式存储之glusterfs

任务背景 实现了远程的存储共享(NAS或SAN)后, 公司业务发展迅速, 存储空间还需要增大。使用NAS或SAN都不方便扩容&#xff0c;NAS可以增加新的挂载目录, SAN可以增加新的硬盘&#xff0c;但我们希望直接在原来挂载的业务目录上实现在线扩容&#xff0c;数据体量越来越大, 这个…

TypeScript中的基本类型

提示&#xff1a;TypeScript中的基本类型 文章目录 前言基本类型1.类型声明2.自动类型判断3.类型断言 前言 TypeScript &#xff08;计算机编程语言&#xff09;简称&#xff1a;TS&#xff0c;是 JavaScript 的超集。简单来说就是&#xff1a;JS 有的 TS 都有。JS写的代码在TS…

UDP分片与丢包,UDP真的比TCP高效吗?

一、UDP 报文格式 每个 UDP 报文分为 UDP 报头和 UDP 数据区两部分。报头由 4 个 16 位长&#xff08;2 字节&#xff09;字段组成&#xff0c;分别说明该报文的源端口、目的端口、报文长度和校验值。 UDP 报文格式如图所示。 UDP 报文中每个字段的含义如下&#xff1a; 源端…

linux下time与dd命令结合测试存储器速度

在Linux中&#xff0c;"time"和"dd"命令是两个独立的命令&#xff0c;它们可以结合使用来测量"dd"命令执行的时间。 下面是它们的简要说明&#xff1a; time命令&#xff1a; "time"命令用于测量命令执行的时间和资源使用情况。它可以…

【操作系统的IO模型有哪些?】

操作系统的IO模型有哪些&#xff1f; 操作系统中的IO模型逐一拓展同步阻塞IO模型同步非阻塞IO模型IO复用模型信号驱动IO模型异步IO模型 操作系统中的IO模型 为了保护操作系统的安全&#xff0c;通过缓存加快系统读写&#xff0c;会将内存分为用户空间和内存空间两个部分。如果…

自动反冲洗过滤器直通式工作原理介绍和附反冲洗原理图动画讲解

​ 1&#xff1a;自动反冲洗过滤器直通式设备介绍 自动反冲洗过滤器是一种先进、高效且易操作的精密设备&#xff0c;广泛应用于冶金、化工、石油、造纸、医药、食品、采矿、电力、城市给水等领域。 在过滤过程中&#xff0c;待过滤的水由进水口进入过滤器机体&#xff0c;流…
最新文章