以前的排序一般对象实现Comparable或者Comparator接口,经常是通过匿名类类实现。
可以参见以前的博文 Java 中 Comparable 和 Comparator 比较
现在看看使用lamda表达式和java8中增强的Comparator接口进行排序。
先定义一个简单的实体类:
class Human {
private String name;
private int age;
public Human() {
super();
}
public Human(final String name, final int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
1.使用lamda表达式或方法引用进行排序
lamda表达式
List<Human> humans = new ArrayList<>();
humans.add(new Human("Sarah", 10));
humans.add(new Human("Jack", 12));
humans.sort((Human h1, Human h2) -> h1.getName().compareTo(h2.getName())); //humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));//简化
当然lamda表达式也可以使用静态方法的引用代替。
public static int compareByNameThenAge(Human lhs, Human rhs) {
if (lhs.name.equals(rhs.name)) {
return lhs.age - rhs.age;
} else {
return lhs.name.compareTo(rhs.name);
}
}
List<Human> humans = new ArrayList<>();
humans.add(new Human("Sarah", 10));
humans.add(new Human("Jack", 12));
humans.sort(Human::compareByNameThenAge);
2.使用增强版的Comparator接口
List<Human> humans = new ArrayList<>();
humans.add(new Human("Sarah", 10));
humans.add(new Human("Jack", 12));
Collections.sort(humans, Comparator.comparing(Human::getName));
还可以使用反转
Collections.sort(humans, Comparator.comparing(Human::getName).reversed());
3.多条件排序
3.1使用lamda表达式
List<Human> humans = new ArrayList<>();
humans.add(new Human("Sarah", 10));
humans.add(new Human("Jack", 12));
humans.add(new Human("Jack", 10));
humans.sort((lhs, rhs) -> { if (lhs.getName().equals(rhs.getName())) { return Integer.compare(lhs.getAge(), rhs.getAge()); } else { return lhs.getName().compareTo(rhs.getName()); } });
3.2使用Comparator进行组合
List<Human> humans = new ArrayList<>();
humans.add(new Human("Sarah", 10));
humans.add(new Human("Jack", 12));
humans.add(new Human("Jack", 10));
humans.sort(Comparator.comparing(Human::getName).thenComparing(Human::getAge));