java中List对象列表去重或取出以及排序

简介: 面试碰到几次list的去重和排序。下面介绍一种做法: 1. list去重 1.1 实体类Student List容量10k以上,要求去重复。这里Student的重复标准是属性相同,因此需要重写equals和hashcode方法,不知道有几个可以手写出来。

面试碰到几次list的去重和排序。下面介绍一种做法:

1. list去重

1.1 实体类Student

List<Student>容量10k以上,要求去重复。这里Student的重复标准是属性相同,因此需要重写equals和hashcode方法,不知道有几个可以手写出来。

student的equals方法:

public void equals(Object o){
  if(this == o) retun true;
  if(!(o instanceof Student)) return false;
  Student stu = (Studend)o;
  if(id!=stu.id) return false;
  if(age!=stu.age) return false;
  return name!=null ? name.equals(stu.name) : stu.name ==null;    
}
View Code

这里只要记住宗旨是比较Student的属性即可,如果属性相同则相等。先考虑地址相等,然后类型匹配instanceof。接下来是各种属性,int属性直接双等号比较,String类型需要判断是否为null,如果是null则都是null返回true,如果不是null则比较equals。

student的hashcode方法:

public int hashCode(){
  int result = id;
  reuslt = 31*id +(name!=null?name.hashCode():0);
  reuslt = 31*age;
  return reuslt;
}
View Code

hashCode是为了hash表计算做辅助,方便快速查找。因此hash算法的结果要尽量的散列。这里用到31,这个31在别的博客中看到的原因是这样的:obj*31==obj<<5-obj.左移5位相当乘以2的5次方,就是32.null的hashCode为空。

通过equals和hashCode的实现可以发现,如果equals为true,则所有属性相同,而属性相同则计算出的hashCode必然相同。然而hashCode相同,属性未必一样,即equals不一定为真。

关于hashCode的价值体现并不在这里,而在于HashMap的实现。HashMap内部是通过链表数组的hash结构来实现的,这里就要用到hashcode。

下面是完整的Student代码:

package com.test.arithmetic.listequals;

/**
 * 这里id,name,age相同则Student相同,
 * 若有其他相同
 * Created by Administrator on 2016/3/29.
 */
public class Student {
    int id;
    String name;
    int age;

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student)) return false;

        Student student = (Student) o;

        if (id != student.id) return false;
        if (age != student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;

    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + age;
        return result;
    }

}
View Code

1.2通过HashSet去重

如果你觉得自己可以hold住一个完善的hash算法就可以自己去实现它。这里采用jdk自带的HashSet来完成重复获取。

先放代码:

package com.test.arithmetic.listequals;
import org.junit.Assert;

import java.util.*;

/**
 * 取出list中重复的Student对象
 * Created by Administrator on 2016/3/29.
 */
public class ObtainListEquals {
    public static void main(String[] args){
        //原始数据
        List<Student> list = new ArrayList<>();
        //重复数据
        List<Student> list2 = new ArrayList<>();
        //填充
        for (int i = 0; i < 10 ; i++) {
            list.add(new Student(i,"_"+i,18+i));
            Random random = new Random();
            if (random.nextBoolean()){
                list.add(new Student(i,"_"+i,18+i));
            }
        }
        //使用hashset去重复,set为重复的集合,可以通过new ArrayList(set)转换成list
        HashSet<Student> set = new HashSet<>();
        for (Student student : list) {
            boolean add = set.add(student);
            if (!add){
                list2.add(student);
            }
        }
        //比较
        Assert.assertEquals(list.size(),list2.size()+set.size());
        
    }

}
View Code

去重的原理和简单,无论你仅仅是想把重复的丢掉,或者将重复的取出来。这里去掉的是第二次遇到的对象,取出的也是第二次遇到的对象。HashSet中的add方法会返回一个Boolean值,如果插入的值已经存在,则直接返回false。关于hashset的源码放到以后研究。大概的说,是通过HashMap的key来实现的,而HashMap在1.8中改动很大,据说是用红黑树实现的,提高了get的时间复杂度。参考:1.8HashMap

 

2. list对象排序

同样list中存放的是Student对象,我需要一个规则来排序。这个排序的规则这里定义为id的比较大小。参考:java中list排序

2.1 Student对象实现Comparable接口

Comparable接口提供一个比较的compareTo(Object o)方法,通过返回值>0,=0,<0比较大小。这里由于仅仅把id当做比较大小的方法,直接用id做减法,如果是要比较对象,建议套用this.property.compareTo(o.property).

package com.test.arithmetic.listequals;

/**
 * 这里id,name,age相同则Student相同,
 * 若有其他相同
 * Created by Administrator on 2016/3/29.
 */
public class Student implements Comparable<Student>{
    int id;
    String name;
    int age;

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student)) return false;

        Student student = (Student) o;

        if (id != student.id) return false;
        if (age != student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;

    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + age;
        return result;
    }

    @Override
    public int compareTo(Student o) {
        return this.id-o.id;
    }
}
View Code

通过Collections.sort(list)排序:

package com.test.arithmetic.list.sort;

import com.test.arithmetic.list.Student;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 对list中对象排序
 * Created by Administrator on 2016/3/29.
 */
public class SortList {
    List<Student> list;
    @Before
    public void setUp(){
        list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            int v = (int)(Math.random() * 100);
            list.add(new Student(v,"_"+v,18+v));
        }
        System.out.println("原list:"+list);
    }
    //方法一,对象实现Comparable接口
    @Test
    public void byImplements(){
        Collections.sort(list);
        System.out.println("排序后:"+list);
    }
}
View Code

2.2 重载sort方法,传入一个比较器

Student类还是未实现Comparable接口之前的:

package com.test.arithmetic.list;

/**
 * 这里id,name,age相同则Student相同,
 * 若有其他相同
 * Created by Administrator on 2016/3/29.
 */
public class Student{
    int id;
    String name;
    int age;

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public Student(int id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student)) return false;

        Student student = (Student) o;

        if (id != student.id) return false;
        if (age != student.age) return false;
        return name != null ? name.equals(student.name) : student.name == null;

    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + age;
        return result;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
View Code

在排序的代码出添加排序规则:

package com.test.arithmetic.list.sort;

import com.test.arithmetic.list.Student;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 对list中对象排序
 * Created by Administrator on 2016/3/29.
 */
public class SortList {
    List<Student> list;
    @Before
    public void setUp(){
        list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            int v = (int)(Math.random() * 100);
            list.add(new Student(v,"_"+v,18+v));
        }
        System.out.println("原list:"+list);
    }
    //方法一,对象实现Comparable接口
    @Test
    public void byImplements(){
//        Collections.sort(list);
        System.out.println("排序后:"+list);
    }

    /*方法二,添加比较器*/
    @Test
    public void byOverideCompare(){

        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getId()-o2.getId();
            }
        });
        System.out.println(list);
    }
}

 





唯有不断学习方能改变! -- Ryan Miao
目录
相关文章
|
1月前
|
存储 Java 程序员
Java判断列表中元素的唯一性
Java判断列表中元素的唯一性
|
21天前
|
Java
java8中List对象转另一个List对象
java8中List对象转另一个List对象
36 0
|
3天前
|
索引 容器
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
06-python数据容器-list列表定义/list的10个常用操作/列表的遍历/使用列表取出偶数
|
11天前
使用Vant框架的组件van-pull-refresh搭配van-list和van-card完成上滑加载更多列表数据,下拉刷新当前列表数据(等同于翻页功能)
使用Vant框架的组件van-pull-refresh搭配van-list和van-card完成上滑加载更多列表数据,下拉刷新当前列表数据(等同于翻页功能)
|
12天前
|
索引 Python
Python标准数据类型-List(列表)
Python标准数据类型-List(列表)
41 1
|
18天前
|
Java
Java使用List去重的四中方式
Java使用List去重的四中方式
16 6
|
22天前
Cause: java.sql.SQLIntegrityConstraintViolationException: Column ‘id‘ in field list is ambiguous
Cause: java.sql.SQLIntegrityConstraintViolationException: Column ‘id‘ in field list is ambiguous
12 0
|
1月前
|
Java
JAVA——List中剔除空元素(null)的三种方法汇总
JAVA——List中剔除空元素(null)的三种方法汇总
|
1月前
|
存储 安全 Java
Python教程第3章 | 集合(List列表、Tuple元组、Dict字典、Set)
Python 列表、无序列表、字典、元组增删改查基本用法和注意事项
50 1
|
1月前
|
安全 Java API
Java并发 - J.U.C并发容器类 list、set、queue
Queue API 阻塞是通过 condition 来实现的,可参考 Java 并发 - Lock 接口 ArrayBlockingQueue 阻塞 LinkedBlockingQueue 阻塞 ArrayQueue 非阻塞 LinkedQueue 非阻塞