Java8 中 Comparator 接口提供了一些静态方法,可以方便于我们进行排序操作,下面通过例子讲解下如何使用

对整数列表排序(升序)

List<Integer> list = Arrays.asList(1, 4, 2, 6, 2, 8);
list.sort(Comparator.naturalOrder());
System.out.println(list);

对整数列表排序(降序)

List<Integer> list = Arrays.asList(1, 4, 2, 6, 2, 8);
list.sort(Comparator.reverseOrder());
System.out.println(list);
public class Test {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("a", 2));
        personList.add(new Person("b", 4));
        personList.add(new Person("c", 7));
        // 升序
        personList.sort(Comparator.comparingInt(Person::getAge));
        // 降序
        personList.sort(Comparator.comparingInt(Person::getAge).reversed());
        System.out.println(personList);
    }

    public static class Person {
        private String name;
        private Integer age;

        public Person(String name, Integer age) {
            this.name = name;
            this.age = age;
        }

        public Integer getAge() {
            return age;
        }

        // ... toString 方法
    }
}
12-21 01:25