以前的排序一般对象实现Comparable或者Comparator接口,经常是通过匿名类类实现。
可以参见以前的博文 Java 中 Comparable 和 Comparator 比较
现在看看使用lamda表达式和java8中增强的Comparator接口进行排序。
先定义一个简单的实体类:
public class Student {
private String name;
private int score;
public Student() {
}
public Student(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}1、使用lamda表达式或方法引用进行排序
List<Student> students = new ArrayList<>();
students.add(new Student("Sarah", 10));
students.add(new Student("Jack", 90));
students.add(new Student("Anson", 30));
students.add(new Student("X-rapido", 10));
students.sort(new Comparator<Student>() { // 匿名内部类写法
@Override
public int compare(Student o1, Student o2) {
return o1.getName().compareTo(o2.getName());
}
});
// 以上代码简写方式
students.sort((h1, h2) -> h1.getName().compareTo(h2.getName()));
students.sort(Comparator.comparing(Student::getName).reversed()); // 翻转排序
// 再进行简写(推荐这种方式)
students.sort(Comparator.comparing(Student::getName));
students.forEach(s -> System.out.println(s.getName() + " : " + s.getScore()));运行结果
Anson : 30 Jack : 90 Sarah : 10 X-rapido : 10
当然lamda表达式也可以使用静态方法的引用代替。
Student中增加2个方法,分别姓名和成绩排序
public int compareByScore(Student student) {
return this.getScore() - student.getScore();
}
public int compareByName(Student student) {
return this.getName().compareToIgnoreCase(student.getName());
}调用方式
// 姓名排序 students.sort(Student::compareByName); // 成绩排序 students.sort(Student::compareByScore);
2、使用增强版的Comparator接口
Collections.sort(students, Comparator.comparing(Student::getName)); // 翻转排序 Collections.sort(students, Comparator.comparing(Student::getName).reversed());
3、Comparator进行组合
students.sort(Comparator.comparing(Student::getName).thenComparing(Student::compareByScore)); Collections.sort(students, Comparator.comparing(Student::getName).thenComparing(Student::getScore));
相关阅读:
【Java】Map集合利用比较器Comparator根据Key和Value的排序
Java中Comparable和Comparator区别小结
未经允许请勿转载:程序喵 » Java8新特性:用lamda表达式和增强版Comparator进行排序
程序喵