Java集合框架自带一个排序的方法sort(),但是需要传入一个比较器对象
我们可以定义一个比较器的类,实现Comparator接口,重写compare方法
1 2 3 4 5 6 7 8 9 10 11 12
| class comparatorAge implements Comparator<User>{ @Override public int compare(User u1, User u2) { if (u1.getAge() > u2.getAge()) { return -1; }else if (u1.getAge() < u2.getAge()){ return 1; } return 0; } }
|
1
| users.sort(new comparatorAge());
|
sort传入比较方法就可以了,但这样写明显是不合理的。
我们可以改进成匿名内部类的形式
1 2 3 4 5 6 7 8 9 10 11
| users.sort(new Comparator<User>() { @Override public int compare(User u1, User u2) { if (u1.getAge() > u2.getAge()){ return -1; }else if (u1.getAge() < u2.getAge()){ return 1; } return 0; } });
|
我们还可以用Java8的新特性lambda表达式优化一下
1 2 3 4 5 6 7 8 9 10
| users.sort((u1,u2)->{ if (u1.getAge() > u2.getAge()){ return -1; }else if (u1.getAge() < u2.getAge()){ return 1; } return 0; });
|
如果存在多个比较规则的话,这样代码写起来会比较困难,我们可以用之前的工厂模式进行简单封装。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| package colltection;
import java.util.Comparator;
public class ComparatorFactort { public final static int AGE_MIN_TO_MAX = 1; public final static int AGE_MAX_TO_MIN = 2; public final static int NAME_MAX_TO_MIN = 3; public final static int NAME_MIN_TO_MAX = 4;
public static Comparator getComparator(int type){ Comparator<User> comparator = null; if (type == AGE_MAX_TO_MIN){ comparator = (p1,p2)->{ if (p1.getAge() > p2.getAge()){ return -1; }else if (p1.getAge() < p2.getAge()){ return 1; }return 0; }; } if (type == AGE_MIN_TO_MAX){ comparator = (p1,p2)->{ if (p1.getAge() > p2.getAge()){ return 1; }else if (p1.getAge() < p2.getAge()){ return -1; } return 0; }; } if (type == NAME_MAX_TO_MIN){ comparator = (p1,p2)-> p1.getName().compareTo(p2.getName()); }
if (type == NAME_MIN_TO_MAX){ comparator = (p1,p2)-> p2.getName().compareTo(p1.getName()); }
return comparator; } }
|