List集合去重的一些方法(常规遍历、Set去重、java8 stream去重、重写equals和hashCode方法)

2019-10-11 20:16:45

参考地址 List集合去重的一些方法(常规遍历、Set去重、java8 stream去重、重写equals和hashCode方法)

1. 常规元素去重(对象去重在下面)

碰到List去重的问题,除了遍历去重,我们常常想到利用Set集合不允许重复元素的特点,通过List和Set互转,来去掉重复元素。

复制代码

// 遍历后判断赋给另一个list集合,保持原来顺序
    public static void ridRepeat1(List<String> list) {
        System.out.println("list = [" + list + "]");
        List<String> listNew = new ArrayList<String>();        for (String str : list) {            if (!listNew.contains(str)) {
                listNew.add(str);
            }
        }
        System.out.println("listNew = [" + listNew + "]");
    }    // set集合去重,保持原来顺序
    public static void ridRepeat2(List<String> list) {
        System.out.println("list = [" + list + "]");
        List<String> listNew = new ArrayList<String>();
        Set set = new HashSet();        for (String str : list) {            if (set.add(str)) {
                listNew.add(str);
            }
        }
        System.out.println("listNew = [" + listNew + "]");
    }    // Set去重     由于Set的无序性,不会保持原来顺序
    public static void ridRepeat3(List<String> list) {
        System.out.println("list = [" + list + "]");
        Set set = new HashSet();
        List<String> listNew = new ArrayList<String>();
        set.addAll(list);
        listNew.addAll(set);
        System.out.println("listNew = [" + listNew + "]");
    }    // Set去重(将ridRepeat3方法缩减为一行) 无序
    public static void ridRepeat4(List<String> list) {
        System.out.println("list = [" + list + "]");
        List<String> listNew = new ArrayList<String>(new HashSet(list));
        System.out.println("listNew = [" + listNew + "]");
    }    // Set去重并保持原先顺序的两种方法
    public static void ridRepeat5(List<String> list) {
        System.out.println("list = [" + list + "]");
        List<String> listNew = new ArrayList<String>(new TreeSet<String>(list));
        List<String> listNew2 = new ArrayList<String>(new LinkedHashSet<String>(list));
        System.out.println("listNew = [" + listNew + "]");
        System.out.println("listNew2 = [" + listNew2 + "]");
    }

复制代码

除此之外,可以利用java8的stream来实现去重

  //利用java8的stream去重
  List uniqueList = list.stream().distinct().collect(Collectors.toList());
  System.out.println(uniqueList.toString());

上面的方法在List元素为基本数据类型及String类型时是可以的,但是如果List集合元素为对象,却不会奏效

复制代码

public class ObjectRidRepeat {    
    public static void main(String[] args) {
        List<User> userList = new ArrayList<User>();
        userList.add(new User("小黄",10));
        userList.add(new User("小红",23));
        userList.add(new User("小黄",78));
        userList.add(new User("小黄",10));        
        //使用HashSet,无序
        Set<User> userSet = new HashSet<User>();
        userSet.addAll(userList);
        System.out.println(userSet);        
        //使用LinkedHashSet,有序
        List<User> listNew = new ArrayList<User>(new LinkedHashSet(userList));
        System.out.println(listNew.toString());
    }
}

复制代码

User类结构如下:

输出如下:(没有去重)

2. 对象去重

 解决对象去重,可以利用for循环遍历的方式进行判断去重,但今天我不准备探究这种方法,要使用的是如下两种:

2.1 使用Java8新特性stream去重

复制代码

        //根据name属性去重
        List<User> unique1 = userList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparing(User::getName))), ArrayList::new));

        System.out.println(unique1.toString());        //根据name,age属性去重
        List<User> unique2 = userList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparing(o -> o.getName() + ";" + o.getAge()))), ArrayList::new)
        );

        System.out.println(unique2.toString());

复制代码

输出如下:

2.2 对象中重写equals()方法和hashCode()方法

 在User类中重写equals()方法和hashCode()方法:

复制代码

 //重写equals方法 @Override    public boolean equals(Object obj) {
        User user = (User) obj;        return name.equals(user.getName()) && (age==user.getAge());
    }//重写hashCode方法    @Override    public int hashCode() {
        String str = name + age;        return str.hashCode();
    }

复制代码

当再次执行通过Set去重的方法时,输出如下:

3. equals()方法和hashCode()方法探究

通过最具代表的的String中的equals()方法和hashCode()方法源码来探究两个方法的实现

3.1 equals()方法

复制代码

/**
     * Compares this string to the specified object.  The result is {@code
     * true} if and only if the argument is not {@code null} and is a {@code
     * String} object that represents the same sequence of characters as this
     * object.
     *
     * @param  anObject
     *         The object to compare this {@code String} against
     *
     * @return  {@code true} if the given object represents a {@code String}
     *          equivalent to this string, {@code false} otherwise
     *
     * @see  #compareTo(String)
     * @see  #equalsIgnoreCase(String)     */
    public boolean equals(Object anObject) {        if (this == anObject) {            return true;
        }        if (anObject instanceof String) {
            String anotherString = (String)anObject;            int n = value.length;            if (n == anotherString.value.length) {                char v1[] = value;                char v2[] = anotherString.value;                int i = 0;                while (n-- != 0) {                    if (v1[i] != v2[i])                        return false;
                    i++;
                }                return true;
            }
        }        return false;
    }

复制代码

比较两个对象时,首先先去判断两个对象是否具有相同的地址,如果是同一个对象的引用,则直接放回true;如果地址不一样,则证明不是引用同一个对象,接下来就是挨个去比较两个字符串对象的内容是否一致,完全相等返回true,否则false。

3.2 hashCode()方法

复制代码

 /**
     * Returns a hash code for this string. The hash code for a
     * {@code String} object is computed as
     * <blockquote><pre>
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * </pre></blockquote>
     * using {@code int} arithmetic, where {@code s[i]} is the
     * <i>i</i>th character of the string, {@code n} is the length of
     * the string, and {@code ^} indicates exponentiation.
     * (The hash value of the empty string is zero.)
     *
     * @return  a hash code value for this object.     */
    public int hashCode() {        int h = hash;        if (h == 0 && value.length > 0) {            char val[] = value;            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }        return h;
    }

复制代码

当equals方法被重写时,通常有必要重写 hashCode 方法,以维护 hashCode 方法的常规协定,该协定声明相等对象必须具有相等的哈希码。

根据《Effective Java》第二版的第九条:覆盖equals时总要覆盖hashCode 中的内容,总结如下:

  • 在程序执行期间,只要equals方法的比较操作用到的信息没有被修改,那么对这同一个对象调用多次,hashCode方法必须始终如一地返回同一个整数。

  • 如果两个对象根据equals方法比较是相等的,那么调用两个对象的hashCode方法必须返回相同的整数结果。

  • 如果两个对象根据equals方法比较是不等的,则hashCode方法不一定得返回不同的整数。但是,程序员应该知道,为不相等的对象生成不同整数结果可以提高哈希表的性能。

《Java编程思想》中也有类似总结:

  设计hashCode()时最重要的因素就是:无论何时,对同一个对象调用hashCode()都应该产生同样的值。如果在讲一个对象用put()添加进HashMap时产生一个hashCdoe值,而用get()取出时却产生了另一个hashCode值,那么就无法获取该对象了。所以如果你的hashCode方法依赖于对象中易变的数据,用户就要当心了,因为此数据发生变化时,hashCode()方法就会生成一个不同的散列码。


  • 2019-07-26 19:31:03

    Guacamole搭建

    因项目需要,经历多天查阅各种文档,几经波折终于功德圆满,写下此篇文章供大家分享。Guacamole就个人理解而言是一个可以通过web浏览器访问远程服务器终端进行操作的可视化工具。主要由web(浏览器)、Guacamole Server(核心)、Remote Desktops(远程桌面)三大模块组成。

  • 2019-07-30 22:36:10

    使用 Spring Initializr 初始化 Spring Boot 项目

    万事开头难,你需要设置一个目录结构存放各种项目内容,创建构建文件,并在其中加入各 种依赖。Spring Boot CLI消除了不少设置工作,但如果你更倾向于传统Java项目结构,那你应该 看看Spring Initializr。

  • 2019-08-06 15:30:08

    小程序展示富文本

    然而rich-text有个问题,它不能够给内联img设置宽度100%,这样图片就容易溢出屏幕。我们只能在后台返回富文本的时候对图片的img标签进行格式化。或者前端进行格式化也行,我赞成使用后端,因为很多种情况我们不一定都能想得到。

  • 2019-08-07 09:07:32

    最全的Service Worker讲解

    Service Worker 最主要的特点是:在页面中注册并安装成功后,运行于浏览器后台,不受页面刷新的影响,可以监听和截拦作用域范围内所有页面的 HTTP 请求。 基于 Service Worker API 的特性,结合 Fetch API、Cache API、Push API、postMessage API 和 Notification API,可以在基于浏览器的 web 应用中实现如离线缓存、消息推送、静默更新等 native 应用常见的功能,以给 web 应用提供更好更丰富的使用体验。

  • 2019-08-07 09:09:19

    windows系统下定时关闭程序

    其中xxx.exe是你要关闭的进程中运行的exe,可以ctrl+alt+del打开任务管理器,进到详细信息查看 然后把.txt文件后缀改成.bat(此时要在查看一栏勾上文件拓展名,要不还是txt文档)

  • 2019-08-07 09:16:43

    一个比较完美的PWA例子

    但就目前来讲,PWA是Google主推的一项技术标准,FireFox,Chrome以及一些基于Blink的浏览器已经支持渐进式Web应用了,Edge上对渐进式Web应用的支持还在开发。Apple公司也表示会考虑在自己Safari支持PWA。然而这项功能已经进入了WebKit内核的五年计划中。长期来看,对浏览器兼容性的支持方面应该已经不算太大问题了。况且在现阶段,在不支持渐进式Web应用的浏览器中,你的应用也只是无法使用渐进式Web应用的离线功能而已,除此之外的功能均可以正常使用。

  • 2019-08-07 09:57:48

    spring data jpa 实体类中字段不与数据库表映射

    当我们使用spring data jpa开发的时候,会将实体类中的成员变量与表中的字段一一对应,当我们在实体类中加上一个不与数据库表一一对应的成员变量的时候,此时我们只要在这个成员变量上加上注解@Transient @