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);
    }
}
相關文章
相關標籤/搜索