使用Java8的Comparator对单个和多个属性进行排序

使用Java8的Comparator进行排序,代码会显得非常简洁,不用像传统方式自定义一个类或定义一个匿名内部类。

Demo演示了基于Person类对单个和多个属性进行排序,其中对多个属性排序,就和数据库的多字段排序一样,先按照A字段升序,A相同则按照B字段降序。
代码:

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * Java8 Comparator排序,演示了单个属性排序和多个属性排序
 *
 * 两个属性排序,先按照A字段升序,A相同则按照B字段降序
 */
public class ComparatorTest1 {

    public static void main(String[] args) {
        Person p1 = new Person();
        p1.setAge(20);
        p1.setName("1");

        Person p2 = new Person();
        p2.setAge(20);
        p2.setName("2");

        Person p3 = new Person();
        p3.setAge(18);
        p3.setName("3");

        Person p4 = new Person();
        p4.setAge(25);
        p4.setName("4");

        Person p5 = new Person();
        p5.setAge(21);
        p5.setName("2");


        List<Person> personList = Arrays.asList(p1, p2, p3, p4, p5);

        //年龄升序排序
        personList.sort(Comparator.comparing(Person::getAge));
        personList.forEach(System.out::println);

        System.out.println("-------------------------------------------");

        //先用年龄升序排序,年龄相同,则按照姓名升序排序
        personList.sort(Comparator.comparing(Person::getAge).thenComparing(Person::getName));
        personList.forEach(System.out::println);

    }
}
/*
年龄升序排序
Person(name=3, age=18, address=null, amount1=null, amount2=null)
Person(name=1, age=20, address=null, amount1=null, amount2=null)
Person(name=2, age=20, address=null, amount1=null, amount2=null)
Person(name=2, age=21, address=null, amount1=null, amount2=null)
Person(name=4, age=25, address=null, amount1=null, amount2=null)
-------------------------------------------
先用年龄升序排序,年龄相同,则按照姓名升序排序
Person(name=3, age=18, address=null, amount1=null, amount2=null)
Person(name=1, age=20, address=null, amount1=null, amount2=null)
Person(name=2, age=20, address=null, amount1=null, amount2=null)
Person(name=2, age=21, address=null, amount1=null, amount2=null)
Person(name=4, age=25, address=null, amount1=null, amount2=null)
 */