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-10-08 13:14:44

    MySQL 批量修改表名

    功能:将数据库 booksystem 中的表名前缀是 sys_ 开头的表名替换 sys_ 为 qun_

  • 2019-10-08 13:26:19

    详解Linux服务器最大tcp连接数

    1全部作为client端的情况下,最大tcp连接数为65535,这些连接可以连到不同的server ip。 2对server端,通过增加内存、修改最大文件描述符个数等参数,单机最大并发TCP连接数超过10万 是没问题的,国外 Urban Airship 公司在产品环境中已做到 50 万并发 。

  • 2019-10-08 14:09:57

    git创建分支并提交到远程分支

    远程分支的创建,一般都是基于本地分支的。即将本地的某个分支提交到远程,作为远程分支。命令如下:

  • 2019-10-09 13:38:20

    NPM依赖包版本号~和^和*的区别

    ~ 会匹配最近的小版本依赖包,比如~1.2.3会匹配所有1.2.x版本,但是不包括1.3.0 ^ 会匹配最新的大版本依赖包,比如^1.2.3会匹配所有1.x.x的包,包括1.3.0,但是不包括2.0.0 * 这意味着安装最新版本的依赖包

  • 2019-10-09 14:39:40

    import双反斜杠\\的意思

    ​ \表示引用根目录下面的PHPEXcel;不用\的话是引用当前目录下面的 PHPExcel

  • 2019-10-09 15:33:31

    nuxt,nuxtjs简单介绍以及使用

    在集成的服务器端框架之间进行选择: 选择您喜欢的 UI 框架: 选择您喜欢的测试框架: 选择你想要的 Nuxt 模式 (Universal or SPA) 添加 axios module 以轻松地将 HTTP 请求发送到您的应用程序中。 添加 EsLint 以在保存时代码规范和错误检查您的代码。 添加 Prettier 以在保存时格式化/美化您的代码。

  • 2019-10-10 00:21:35

    laravel 5.6以上日志理解及日志格式定义

    Laravel/Lumen的日志默认是基于Monolog进行了一层封装,如果要求不高,用起来还是十分容易的,本文基于laravel5.6/Lumen5.6版本进行解说。5.6版对日志系统做了升级,将日志的配置单独放以了config/logging.php 配置文件中,所以现在实用多了。

  • 2019-10-10 10:10:49

    @Scheduled注解各参数详解

    每隔5秒执行一次:*/5 * * * * ? 每隔1分钟执行一次:0 */1 * * * ? 每天23点执行一次:0 0 23 * * ? 每天凌晨1点执行一次:0 0 1 * * ? 每月1号凌晨1点执行一次:0 0 1 1 * ? 每月最后一天23点执行一次:0 0 23 L * ? 每周星期天凌晨1点实行一次:0 0 1 ? * L 在26分、29分、33分执行一次:0 26,29,33 * * * ? 每天的0点、13点、18点、21点都执行一次:0 0 0,13,18,21 * * ?