一、普通排序:
1 @Test 2 public void testComparator() { 3 List<Integer> list = Arrays.asList(1, 9, 3, 5, 0, 8); 4 list.sort(Comparator.naturalOrder()); 5 System.out.println("升序:" + list); 6 7 list.sort(Comparator.reverseOrder()); 8 System.out.println("降序:" + list); 9 }
结果为:
升序:[0, 1, 3, 5, 8, 9]
降序:[9, 8, 5, 3, 1, 0]
二、根据对象属性排序:
1.根据属性排序
1 public void testComparator() { 2 List<Person> personList = new ArrayList<>(); 3 personList.add(new Person("Tom", 2)); 4 personList.add(new Person("Jerry", 4)); 5 personList.add(new Person("Lucy", 7)); 6 personList.add(new Person("Lily", 7)); 7 8 // 年龄升序 9 personList.sort(Comparator.comparing(Person::getAge)); 10 System.out.println("年龄升序:" + personList); 11 12 // 年龄降序 13 personList.sort(Comparator.comparing(Person::getAge).reversed()); 14 System.out.println("年龄降序:" + personList); 15 16 // 先年龄降序再名字升序 17 personList.sort(Comparator.comparing(Person::getAge).reversed().thenComparing(Person::getName)); 18 System.out.println("先年龄降序再名字升序:" + personList); 19 }
person对象:
1 public class Person { 2 private String name; 3 private Integer age; 4 5 public Person(String name, Integer age) { 6 this.name = name; 7 this.age = age; 8 } 9 10 public Integer getAge() { 11 return age; 12 } 13 14 @Override 15 public String toString() { 16 return "Person [name=" + name + ", age=" + age + "]"; 17 } 18 }
结果为:
年龄升序:[Person [name=Tom, age=2], Person [name=Jerry, age=4], Person [name=Lucy, age=7], Person [name=Lily, age=7]]
年龄降序:[Person [name=Lucy, age=7], Person [name=Lily, age=7], Person [name=Jerry, age=4], Person [name=Tom, age=2]]
先年龄降序再名字升序:[Person [name=Lily, age=7], Person [name=Lucy, age=7], Person [name=Jerry, age=4], Person [name=Tom, age=2]]
2.根据属性类型排序
根据int double 。。。排序 :即根据对象的 int double 。。。排序;
例如:
Comparator.comparingInt(Person::getAge).reversed().thenComparing(Person::getName))
3.排序对象存在null的情况:
1 @Test 2 public void testComparator() { 3 List<Person> personList = new ArrayList<>(); 4 personList.add(new Person("Tom", 2)); 5 personList.add(new Person("Jerry", 4)); 6 personList.add(new Person("Lucy", 7)); 7 personList.add(new Person("Lily", 7)); 8 9 personList.add(null); 10 // null的排序 11 personList.sort( 12 Comparator.nullsFirst(Comparator.comparing(Person::getAge).reversed().thenComparing(Person::getName))); 13 System.out.println("null排第一:" + personList); 14 }