List集合的排序方式
本文主要讲述Lsit集合的排序方式:
1 /** 2 * 集合的排序方式:2种方式 3 */ 4 public class GenericWork { 5 public static void main(String[] args) { 6 ArrayList<Employee> employeeArrayList = new ArrayList<>(); 7 employeeArrayList.add(new Employee("tom",20000,2000,12,4)); 8 employeeArrayList.add(new Employee("jack",18000,2002,2,10)); 9 employeeArrayList.add(new Employee("white",8000,2001,8,5)); 10 employeeArrayList.add(new Employee("jack",18000,2002,1,5)); 11 employeeArrayList.add(null); 12 13 // 排序方式1: 14 // Collections.sort(employeeArrayList, new Comparator<Employee>() { 15 // @Override 16 // public int compare(Employee o1, Employee o2) { 17 // int res = o1.getName().compareTo(o2.getName()); 18 // if(res == 0){ 19 // res = o1.getBirthday().compareTo(o2.getBirthday()); 20 // } 21 // return res; 22 // } 23 // }); 24 25 // 排序方式2: 26 employeeArrayList.sort(new Comparator<Employee>() { 27 @Override 28 public int compare(Employee o1, Employee o2) { 29 if(o1 == null || o2 == null){ 30 return 0; 31 } 32 int res = o1.getName().compareTo(o2.getName()); 33 if(res == 0){ 34 res = o1.getBirthday().compareTo(o2.getBirthday()); 35 } 36 return res; 37 } 38 }); 39 40 // 遍历 41 Iterator<Employee> iterator = employeeArrayList.iterator(); 42 while (iterator.hasNext()) { 43 Employee employee = iterator.next(); 44 if(employee != null){ 45 System.out.println(employee); 46 } 47 } 48 } 49 } 50 // 注意这里实现Comparable接口泛型的使用 51 class MyDate implements Comparable<MyDate>{ 52 private int year; 53 private int mon; 54 private int day; 55 56 public MyDate(int year, int mon, int day) { 57 this.year = year; 58 this.mon = mon; 59 this.day = day; 60 } 61 62 @Override 63 public int compareTo(MyDate date) { 64 int res = this.year - date.year; 65 if(res == 0){ 66 res = this.mon - date.mon; 67 } 68 if(res == 0){ 69 res = this.day - date.day; 70 } 71 return res; 72 } 73 74 @Override 75 public String toString() { 76 return "year=" + year + 77 ", mon=" + mon + 78 ", day=" + day ; 79 } 80 } 81 82 class Employee { 83 private String name; 84 private double sal; 85 private MyDate birthday; 86 87 public Employee(String name, double sal, int year,int mon,int day) { 88 this.name = name; 89 this.sal = sal; 90 this.birthday = new MyDate(year,mon,day); 91 } 92 93 public String getName() { 94 return name; 95 } 96 97 public void setName(String name) { 98 this.name = name; 99 } 100 101 public MyDate getBirthday() { 102 return birthday; 103 } 104 105 @Override 106 public String toString() { 107 return "Employee{" + 108 "name='" + name + '\'' + 109 ", sal=" + sal + 110 ", birthday: " + birthday + 111 '}'; 112 } 113 }
总结:
方式1:Collections工具类的sort()方法,使用匿名内部类,实现Comparator接口,实现接口的compare()方法,并且要求比较的对象类实现Comparable接口,实现接口的compareTo()方法。
方式2:List类的sort()方法,使用匿名内部类,实现Comparator接口,实现接口的compare()方法,并且要求比较的对象类实现Comparable接口,实现接口的compareTo()方法。
注意:使用泛型的好处,使得List集合只能添加泛型指定的类的对象,否则编译报错。但是null仍然能够添加【list.add(null)】,因此需要在compare(Employee o1,Employee o2)中,判断传入的o1和o2是否为空,若为空,则不进行比较,直接返回0,否则有空指针异常【运行时异常】。