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

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

1. list去重

1.1 实体类Student

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

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为空。dom

经过equals和hashCode的实现能够发现,若是equals为true,则全部属性相同,而属性相同则计算出的hashCode必然相同。然而hashCode相同,属性未必同样,即equals不必定为真。ide

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

下面是完整的Student代码:spa

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来完成重复获取。3d

先放代码:

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);
    }
}
相关文章
相关标签/搜索