Comparator 对对象排序的优先顺序的定义:
返回的数字越大排名越靠前
eg:一个对象有三个属性,年龄,工资,销售量
如果设定一个排序规则,
优先排序规则:
年龄从小到大、
工资从大到小
销量从高到底
该怎么排
下面插入代码,先定义一个类
class User { private int age; private int salary; private int sales; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getSalary() { return salary; } public void setSalary(int salary) { this.salary = salary; } public int getSales() { return sales; } public void setSales(int sales) { this.sales = sales; } public User(int age,int salary,int sales) { super(); this.age = age; this.salary = salary; this.sales = sales; } @Override public String toString() { return "User [age=" + age + ", salary=" + salary + ", sales=" + sales + "]"; } }
写一个测试类:
public class ComparatorTest { public static void main(String[] args) { User u1 = new User(11, 22, 33); User u2 = new User(11, 22, 34); User u3 = new User(11, 22, 35); User u4 = new User(21, 22, 33); User u5 = new User(31, 22, 33); User u6 = new User(41, 22, 33); User u7 = new User(51, 220, 33); User u8 = new User(51, 222, 33); User u9 = new User(51, 226, 77); User u10 = new User(51, 226, 33); User u11 = new User(11, 22, 33); List<User> ulist = new ArrayList<User>(); ulist.add(u11); ulist.add(u10); ulist.add(u9); ulist.add(u8); ulist.add(u7); ulist.add(u6); ulist.add(u5); ulist.add(u4); ulist.add(u3); ulist.add(u2); ulist.add(u1); Collections.sort(ulist, comparator); for (User user : ulist) { System.out.println(user); } } public static Comparator<User> comparator = new Comparator<User>() { @Override public int compare(User o1, User o2) { // 优先排序规则: // 年龄从小到大、 // 工资从大到小 // 销量从高到底 int a = o1.getAge() - o2.getAge(); if (a != 0) { return a > 0 ? 3 : -1;// } else { a = o2.getSalary() - o1.getSalary(); if (a != 0) { return a > 0 ? 2 : -2; } else { return o2.getSales() - o1.getSales() > 0 ? 1 : -3; } } } }; } }
以此类推,
打印结果
User [age=11, salary=22, sales=35] User [age=11, salary=22, sales=34] User [age=11, salary=22, sales=33] User [age=11, salary=22, sales=33] User [age=21, salary=22, sales=33] User [age=31, salary=22, sales=33] User [age=41, salary=22, sales=33] User [age=51, salary=226, sales=77] User [age=51, salary=226, sales=33] User [age=51, salary=222, sales=33] User [age=51, salary=220, sales=33]