本文主要是利用java8来对List进行排序:
通过举例进行讲解,首先创建一个简单实例: public class Student implements Comparable{ private String name; private Integer age; private Float score; public Student() { } public Student(String name, Integer age, Float score) { this.name = name; this.age = age; this.score = score; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Float getScore() { return score; } public void setScore(Float score) { this.score = score; } @Override public int compareTo(Student o) { return this.getScore().compareTo(o.getScore()); } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + ", score=" + score + '}'; } }
添加几个测试数据: List students = new ArrayList<>(); Student xiaoming = new Student("小明", 13, 186.5f); Student xiaoxi = new Student("小茜", 14, 191f); Student xiaoyi = new Student("小艺", 12, 188.5f); Student xiaolan = new Student("小兰", 15, 188.5f); students.add(xiaoming); students.add(xiaoxi); students.add(xiaoyi); students.add(xiaolan);
1.由于Student类实现了Comparable接口,因此可以直接使用 Collections.sort(students); 或 students.sort(Student::compareTo);
2. 可以使用匿名内部类进行排序 Collections.sort(students, new Comparator() { @Override public int compare(Student o1, Student o2) { return o1.getScore().compareTo(o2.getScore()); } }); 或 students.sort(new Comparator() { @Override public int compare(Student o1, Student o2) { return o1.getScore().compareTo(o2.getScore()); } });
3.使用Lambda表达式进行排序 Collections.sort(students, (x, y) -> x.getScore().compareTo(y.getScore()));
4.使用Comparator.comparing方法
我们使用上述lambda表达式的时候,IDE会提示我们:can be replaced with comparator.comparing Collections.sort(students, Comparator.comparing(Student::getScore));
5.使用方法引用排序(我们创建Student的时候实现了compareTo方法) students.sort(Student::compareTo);
我们还可以很方便的进行反转排序 Comparator comparator = Comparator.comparing(Student::getScore); students.sort(comparator.reversed());
多条件排序,先根据分数,分数相等时再根据名字排序 students.sort((x,y)->{ if(x.getScore().equals(y.getScore())){ return x.getName().compareTo(y.getName()); }else { return x.getScore().compareTo(y.getScore()); } });
或多条件组合排序 students.sort(Comparator.comparing(Student::getScore).thenComparing(Student::getName)); 或 Collections.sort(students,Comparator.comparing(Student::getScore).thenComparing(Student::getName));