一、Comparable的用法
当对java中的某个类的对象要进行排序比较,有两种实现方法,第一种就是类实现Comparable接口,重写compareTo方法,编写排序的逻辑。下面介绍这种方法:
举例:
1 package com.guolele.web.util; 2 3 /** 4 * Created by luotong 2016/8/22. 5 */ 6 public class Person implements Comparable<Person>{ 7 private String name; 8 private int age; 9 private int sal; 10 11 public Person() { 12 } 13 14 public Person(int age,String name,int sal) { 15 this.age = age; 16 this.name = name; 17 this.sal = sal; 18 } 19 20 public String getName() { 21 return name; 22 } 23 24 public void setName(String name) { 25 this.name = name; 26 } 27 28 public int getAge() { 29 return age; 30 } 31 32 public void setAge(int age) { 33 this.age = age; 34 } 35 36 public int getSal() { 37 return sal; 38 } 39 40 public void setSal(int sal) { 41 this.sal = sal; 42 } 43 44 @Override 45 public int compareTo(Person p) { 46 // 先按年龄排,再按姓名排,再按工资排 47 int com = Integer.valueOf(this.age).compareTo(Integer.valueOf(p.age)); 48 if (com != 0) { 49 return com; 50 } 51 com = this.name.compareTo(p.name); 52 if (com != 0) { 53 return com; 54 } 55 return Integer.compare(this.sal,p.sal); 56 } 57 }
二、自定义比较器,实现Comparator接口
自定义比较器更加的灵活,实现Comparator接口要重写compare方法
举例:
1 package com.guolele.web.util; 2 3 import java.util.Comparator; 4 5 /** 6 * Created by luotong on 2016/8/22. 7 * 8 * 自定义比较器 9 */ 10 public class PersionComparator implements Comparator<Person>{ 11 12 @Override 13 public int compare(Person p1, Person p2) { 14 // 先按年龄排,再按姓名排,再按工资排 15 int com = Integer.valueOf(p1.getAge()).compareTo(Integer.valueOf(p2.getAge())); 16 if (com != 0) { 17 return com; 18 } 19 com = p1.getName().compareTo(p2.getName()); 20 if (com != 0) { 21 return com; 22 } 23 return Integer.compare(p1.getSal(),p2.getSal()); 24 } 25 }
三、利用Guava中的ComparisonChain抽象类实现多个属性排序
上面的两种方式代码更加的琐碎,容易搞乱,也不容易调试,而使用Guava的ComparisonChain抽象类的Fluent风格可读性更高,发生错误编码的几率更小。
举例:
package com.guolele.web.util; import com.google.common.collect.ComparisonChain; import java.util.Comparator; /** * Created by luotong on 2016/8/22. * * 自定义比较器,利用Guava中的ComparisonChain抽象类实现 */ public class PersionComparator implements Comparator<Person>{ @Override public int compare(Person p1, Person p2) { // 先按年龄排,再按姓名排,再按工资排 return ComparisonChain.start() .compare(p1.getAge(), p2.getAge()) .compare(p1.getName(),p2.getName()) .compare(p1.getSal(),p2.getSal()) .result(); } }
*** ComparisonChain对多个属性同时排序只能同时升序或者同时降序,如果要灵活排序建议用初始的方法,比如:方法二;