为什么写?


  • comparatorjavase中的接口,位于java.util包下,该接口抽象度极高,有必要掌握该接口的使用
  • 大多数文章告诉大家comparator是用来排序,但我想说排序是comparator能实现的功能之一,他不仅限于排序

接口功能


Comparator接口代表一个比较器,比较器具有可比性!平时我们大多数都是使用改接口(Comparator)实现对集合,排序。这是
因为JAVASE数组工具类和集合工具类中提供的sort方法sort就是使用Comparator接口来处理排序的,但是Comparator接口并不只是
用来排序的,下面是JAVASE一些使用到Comparator接口的地方:

  1. Arrays.sort(T[],Comparator<? super T> c);
  2. Collections.sort(List<T> list,Comparator<? super T> c);

使用场景


什么场景需要做比较,那么什么场景就是Comparator接口的用武之地,我总结的两个场景:

  1. 排序,需要比较两个对象谁排在前谁排在后(排序也可以让类实现Comparable接口,实现后该类的实例也具有排序能力)。
  2. 分组,需要比较两个对象是否是属于同一组。

排序场景

在List或数组中的对象如果没有实现Comparable接口时,那么就需要调用者为需要排序的数组或List设置一个Compartor,Compartor的compare方法用来告诉代码应该怎么去比较两个实例,然后根据比较结果进行排序。

条件排序:公共代码

  1. public class SortTest {
  2. @Data
  3. @AllArgsConstructor
  4. @ToString
  5. class Dog{ //内部类
  6. public int age;
  7. public String name;
  8. public String num;
  9. }
  10. List<Dog> list= new ArrayList<Dog>(){
  11. {
  12. add(new Dog(5, "DogA","001"));
  13. add(new Dog(5, "DogB","002"));
  14. add(new Dog(5, "DogC","003"));
  15. add(new Dog(9, "DogA","004"));
  16. add(new Dog(35, "DogF","005"));
  17. add(new Dog(74, "Dogg","006"));
  18. }
  19. };
  20. }

单一条件排序

Comparator实现排序(按照年龄,名字)

  1. /**
  2. *单一条件排序
  3. */
  4. @Test
  5. public void test1(){
  6. //按照年龄排序
  7. Collections.sort(list, new Comparator<Dog>() {
  8. //实现compare(T o1, To2) 方法,返回正数,零,负数各代表大于,等于小于
  9. @Override
  10. public int compare(Dog o1, Dog o2) {
  11. //return o2.age - o1.age; //排序规则----升序
  12. return String.valueOf(o1.getAge()).compareTo(String.valueOf(o2.getAge())); //compareTo()传String
  13. }
  14. });
  15. System.out.println("给狗狗按照年龄倒序:"+list);
  16. }
  17. @Test
  18. public void test2(){
  19. //按照名字排序
  20. Collator comparator = Collator.getInstance(Locale.CANADA);
  21. Collections.sort(list, new Comparator<Dog>() {
  22. @Override
  23. public int compare(Dog o1, Dog o2) {
  24. // return o1.name.compareTo(o2.name);
  25. return comparator.compare(o1.getName(),o2.getName());
  26. }
  27. });
  28. System.out.println("给狗狗按名字字母顺序排序:"+list);
  29. }

Lambda优化实现排序

  1. /**
  2. *使用Lambda表达式优化比较器代码(单一条件排序)
  3. */
  4. @Test
  5. public void test3() {
  6. //对学生集合按年龄进行排序
  7. Collections.sort(list,(s1, s2) -> (s1.getAge() - s2.getAge()) );
  8. }

多条件排序

Comparator实现排序(按照年龄和名字)

  1. /**
  2. *多条件排序
  3. */
  4. @Test
  5. public void test4() {
  6. Collections.sort(list,new Comparator<Dog>() {
  7. @Override
  8. public int compare(Dog s1, Dog s2) {
  9. int flag;
  10. // 首选按年龄升序排序
  11. flag = s1.getAge()-s2.getAge();
  12. if(flag==0){
  13. // 如果年龄按编号降序排序
  14. flag = s2.getNum().compareTo(s1.getNum());
  15. }
  16. return flag;
  17. }
  18. });
  19. list.forEach(System.out::println);
  20. }

Lambda优化实现多条件排序

  1. /**
  2. *多条件排序 ----使用lambda表达式优化
  3. */
  4. @Test
  5. public void test5() {
  6. Collections.sort(list,(s1,s2)->{
  7. int flag;
  8. // 首选按年龄升序排序
  9. flag = s1.getAge()-s2.getAge();
  10. // 方案一、判断是否为空 --- 为空执行lambda表达式,返回一个对象
  11. flag = Optional.ofNullable(flag == 0 ? null: flag).orElseGet(() -> s2.getNum().compareTo(s1.getNum()));
  12. //方案二、
  13. if(flag==0){
  14. // 如果年龄按编号降序排序
  15. flag =s2.getNum().compareTo(s1.getNum());
  16. }
  17. //最终返回
  18. return flag;
  19. });
  20. list.forEach(System.out::println);
  21. }

自定义条件排序

自定义条件排序公共代码


  1. /**
  2. *自定义条件排序
  3. */
  4. //定义排序规则 通过asList()方法将数组转为list集合
  5. String[] order = {"语文","数学","英语","物理","化学","生物","政治","历史","地理","总分"};
  6. final List<String> definedOrder = Arrays.asList(order);
  7. //需要排序的数据
  8. List<String> listClass = new ArrayList<String>(){
  9. {
  10. add("总分");
  11. add("英语");
  12. add("政治");
  13. add("总分");
  14. add("数学");
  15. }
  16. };

自定义条件排序方案一 Comparator

  1. //自定义条件排序方案一
  2. @Test
  3. public void test6(){
  4. Collections.sort(listClass,new Comparator<String>() {
  5. @Override
  6. public int compare(String o1, String o2) {
  7. //int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。
  8. int io1 = definedOrder .indexOf(o1);
  9. int io2 = definedOrder .indexOf(o2);
  10. return io1-io2;
  11. }
  12. });
  13. for(String s:listClass){
  14. System.out.print(s+" ");
  15. }
  16. //打印结果:数学 英语 政治 总分 总分
  17. }

自定义条件排序方案二 Lambda

  1. //自定义条件排序方案二 使用Lambda表达式优化比较器代码
  2. @Test
  3. public void test7(){
  4. Collections.sort(listClass,(s1,s2)->definedOrder.indexOf(s1) - definedOrder.indexOf(s2));
  5. listClass.forEach(System.out::print);
  6. }

分组场景


使用Comparatorfor循环处理列表,来进行分类;通过调用者实现Comparator接口的比较逻辑,来告诉程序应该怎么比较,通过比较之后得结果来进行分组。
———————————————————————————————————————————————————————————————————————————————————————-
下面例子中分别按照狗狗的颜色和体重级别两个维度来进行分组,因此分组的核心逻辑其实就是比较逻辑。相面我抽了一个工具方法:dividerList,第一个参数为需要处理的数据源,第二参数是分组时的比较逻辑。

公共代码

  1. @Data
  2. @AllArgsConstructor
  3. @ToString
  4. class Apple {
  5. public String color;
  6. public int weight;
  7. }
  8. List<Apple> list = new ArrayList<Apple>(){
  9. {
  10. add(new Apple("红", 205));
  11. add(new Apple("红", 131));
  12. add(new Apple("绿", 248));
  13. add(new Apple("绿", 22));
  14. add(new Apple("黄", 119));
  15. add(new Apple("黄", 224));
  16. add(new Apple("白", 2024));
  17. }
  18. };
  19. /**
  20. * 是否为同一组的判断标准 参数一:需要处理的数据源 datas,参数二分组时的比较逻辑c
  21. */
  22. public static <T> List<List<T>> divider(Collection<T> datas, Comparator<? super T> c) {
  23. List<List<T>> result = new ArrayList<List<T>>();
  24. for (T t : datas) {
  25. boolean isSameGroup = false;
  26. for (int j = 0; j < result.size(); j++) {
  27. if (c.compare(t, result.get(j).get(0)) == 0) {
  28. isSameGroup = true;
  29. result.get(j).add(t);
  30. break;
  31. }
  32. }
  33. if (!isSameGroup) {
  34. // 创建
  35. List<T> innerList = new ArrayList<T>();
  36. result.add(innerList);
  37. innerList.add(t);
  38. }
  39. }
  40. return result;
  41. }

Comparator实现按颜色分组

  1. @Test
  2. public void test1(){
  3. List<List<Apple>> byColors = divider(list, new Comparator<Apple>() {
  4. //按照颜色基本进行分组
  5. @Override
  6. public int compare(Apple o1, Apple o2) {
  7. // 按颜色分组
  8. return o1.color.compareTo(o2.color);
  9. }
  10. });
  11. System.out.println("按颜色分组" + byColors);
  12. }

Lambda优化按颜色分组

  1. /**
  2. *使用lambda优化(按照颜色分组)
  3. */
  4. @Test
  5. public void test1_1() {
  6. //按照颜色重量级分组
  7. divider_Lambda(list, (o1, o2) -> o1.color.compareTo(o2.color)).forEach(System.out::println);
  8. }

Comparator实现按分组

  1. @Test
  2. public void test2(){
  3. //按照重量级进行分组
  4. List<List<Apple>> byWeight = divider(list, new Comparator<Apple>() {
  5. @Override
  6. public int compare(Apple o1, Apple o2) {
  7. // 按重量级
  8. return (o1.getWeight() / 100 == o2.getWeight() / 100) ? 0 : 1;
  9. }
  10. });
  11. byWeight.forEach(x-> System.out.println("按照总量分组:"+x));
  12. //System.out.println("按重量级分组" + byWeight);
  13. }

Lambda优化按重量级分组

  1. /**
  2. *使用lambda优化(按照重量级进行分组)
  3. */
  4. @Test
  5. public void test2_1() {
  6. //按照颜色分组
  7. divider_Lambda(list, (o1, o2) -> (o1.getWeight() / 100 == o2.getWeight() / 100) ? 0 : 1).forEach(System.out::println);
  8. }

Comparator接口常用的方法

公共代码

实体类

Persons实体类

  1. package com.zy.pagehelper.model;
  2. import lombok.Builder;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import java.math.BigDecimal;
  6. @Data
  7. @NoArgsConstructor
  8. @Builder
  9. public class Persons implements Comparable {
  10. private String name;
  11. private BigDecimal age;
  12. private Integer height;
  13. private Student student;
  14. public Persons(String name, BigDecimal age, Integer height) {
  15. this.name = name;
  16. this.age = age;
  17. this.height = height;
  18. this.student = new Student(0);
  19. }
  20. public Persons(String name, BigDecimal age, Integer height, Student student) {
  21. this.name = name;
  22. this.age = age;
  23. this.height = height;
  24. this.student = student;
  25. }
  26. @Override
  27. public int compareTo(Object o) {
  28. Persons p1 = (Persons) o;
  29. if (this.age.equals(p1.age)) {
  30. return p1.height - this.height;
  31. }
  32. return this.age.compareTo(p1.age);
  33. }
  34. }

Student实体类

  1. package com.zy.pagehelper.model;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import java.util.Comparator;
  6. @Data
  7. @AllArgsConstructor
  8. @NoArgsConstructor
  9. public class Student implements Comparator {
  10. private int age;
  11. @Override
  12. public int compare(Object o1, Object o2) {
  13. Student p1 = (Student) o1;
  14. Student p2 = (Student) o2;
  15. int result = Integer.compare(p1.age, p2.age);
  16. result = result == 0 ? ((p1.age > p2.age) ? 1 : -1) : result;
  17. return result;
  18. }
  19. }

公共集合

  1. Persons persons = new Persons();
  2. List<Persons> personList = new ArrayList<Persons>() {
  3. {
  4. add(new Persons("a", new BigDecimal(12), 170));
  5. add(new Persons("b", new BigDecimal(24), 175, new Student(27)));
  6. add(new Persons("c", new BigDecimal(12), 177));
  7. add(new Persons("a", new BigDecimal(12), 177));
  8. add(new Persons("b", new BigDecimal(54), 174, new Student(19)));
  9. }
  10. };

naturalOrder 方法


naturalOrder - 自然比较,根据实体类定义的Comparable进行比较!

示例代码:

  1. @Test
  2. public void testNaturalOrder(){
  3. // naturalOrder 自然比较,根据实体类定义的Comparable
  4. System.out.println("naturalOrder : ");
  5. personList.sort(Comparator.naturalOrder());
  6. personList.forEach(System.out::println);
  7. }

comparing方法


comparing、comparingLong、comparingInt、comparingDouble - 常用比较方法,可以指定参数类型
comparing方法参数是一个函数式接口keyExtractor,意识即为指定排序对象中的排序键,这里注意排序键这里标注了Comparable接口
comparing方法

  1. /**
  2. * Accepts a function that extracts a {@link java.lang.Comparable
  3. * Comparable} sort key from a type {@code T}, and returns a {@code
  4. * Comparator<T>} that compares by that sort key.
  5. *
  6. * <p>The returned comparator is serializable if the specified function
  7. * is also serializable.
  8. *
  9. * @apiNote
  10. * For example, to obtain a {@code Comparator} that compares {@code
  11. * Person} objects by their last name,
  12. *
  13. *
  14. <pre>{@code
  15. * Comparator<Person> byLastName = Comparator.comparing(Person::getLastName);
  16. * }</pre>
  17. */
  18. public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
  19. Function<? super T, ? extends U> keyExtractor)
  20. {
  21. Objects.requireNonNull(keyExtractor);
  22. return (Comparator<T> & Serializable)
  23. (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
  24. }

comparing方法参数是一个函数式接口keyExtractor,意识即为指定排序对象中的排序键,这里注意排序键这里标注了Comparable接口。
同时我们也可以看到有重载的comparing方法:

  1. /**
  2. * Accepts a function that extracts a sort key from a type {@code T}, and
  3. * returns a {@code Comparator<T>} that compares by that sort key using
  4. * the specified {@link Comparator}.
  5. *
  6. * <p>The returned comparator is serializable if the specified function
  7. * and comparator are both serializable.
  8. *
  9. * @apiNote
  10. * For example, to obtain a {@code Comparator} that compares {@code
  11. * Person} objects by their last name ignoring case differences,
  12. *
  13. *
  14. <pre>{@code
  15. * Comparator<Person> cmp = Comparator.comparing(
  16. * Person::getLastName,
  17. * String.CASE_INSENSITIVE_ORDER);
  18. * }</pre>
  19. */
  20. public static <T, U> Comparator<T> comparing(
  21. Function<? super T, ? extends U> keyExtractor,
  22. Comparator<? super U> keyComparator)
  23. {
  24. Objects.requireNonNull(keyExtractor);
  25. Objects.requireNonNull(keyComparator);
  26. return (Comparator<T> & Serializable)
  27. (c1, c2) -> keyComparator.compare(keyExtractor.apply(c1),
  28. keyExtractor.apply(c2));
  29. }

第二个参数也很好理解,提取完sort key之后,要定义关于这个key的Comparator,在注释中的例子也比较好理解。 这里有个小tips:在String类中,提供了一个实现Comparator接口的常量来标识不对语言敏感的字典序排序器。

  1. /**
  2. * A Comparator that orders {@code String} objects as by
  3. * {@code compareToIgnoreCase}. This comparator is serializable.
  4. * <p>
  5. * Note that this Comparator does <em>not</em> take locale into account,
  6. * and will result in an unsatisfactory ordering for certain locales.
  7. * The java.text package provides <em>Collators</em> to allow
  8. * locale-sensitive ordering.
  9. *
  10. * @see java.text.Collator#compare(String, String)
  11. * @since 1.2
  12. */
  13. public static final Comparator<String> CASE_INSENSITIVE_ORDER
  14. = new CaseInsensitiveComparator();
  15. private static class CaseInsensitiveComparator
  16. implements Comparator<String>, java.io.Serializable {
  17. // use serialVersionUID from JDK 1.2.2 for interoperability
  18. private static final long serialVersionUID = 8575799808933029326L;
  19. public int compare(String s1, String s2) {
  20. int n1 = s1.length();
  21. int n2 = s2.length();
  22. int min = Math.min(n1, n2);
  23. for (int i = 0; i < min; i++) {
  24. char c1 = s1.charAt(i);
  25. char c2 = s2.charAt(i);
  26. if (c1 != c2) {
  27. c1 = Character.toUpperCase(c1);
  28. c2 = Character.toUpperCase(c2);
  29. if (c1 != c2) {
  30. c1 = Character.toLowerCase(c1);
  31. c2 = Character.toLowerCase(c2);
  32. if (c1 != c2) {
  33. // No overflow because of numeric promotion
  34. return c1 - c2;
  35. }
  36. }
  37. }
  38. }
  39. return n1 - n2;
  40. }
  41. /** Replaces the de-serialized object. */
  42. private Object readResolve() { return CASE_INSENSITIVE_ORDER; }
  43. }
  44. // 这里其实可以看到compareToIgnoreCase也是调用了这个实例的compare方法
  45. public int compareToIgnoreCase(String str) {
  46. return CASE_INSENSITIVE_ORDER.compare(this, str);
  47. }

在Comparator接口中,也直接提供了具体类型的三个comparing方法:

  1. public static <T> Comparator<T> comparingInt(ToIntFunction<? super T> keyExtractor) {
  2. Objects.requireNonNull(keyExtractor);
  3. return (Comparator<T> & Serializable)
  4. (c1, c2) -> Integer.compare(keyExtractor.applyAsInt(c1), keyExtractor.applyAsInt(c2));
  5. }
  6. public static <T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor) {
  7. Objects.requireNonNull(keyExtractor);
  8. return (Comparator<T> & Serializable)
  9. (c1, c2) -> Long.compare(keyExtractor.applyAsLong(c1), keyExtractor.applyAsLong(c2));
  10. }
  11. public static<T> Comparator<T> comparingDouble(ToDoubleFunction<? super T> keyExtractor) {
  12. Objects.requireNonNull(keyExtractor);
  13. return (Comparator<T> & Serializable)
  14. (c1, c2) -> Double.compare(keyExtractor.applyAsDouble(c1), keyExtractor.applyAsDouble(c2));
  15. }

测试示例代码:

  1. @Test
  2. public void testComparing(){
  3. //comparing、comparingLong、comparingInt、comparingDouble - 常用比较方法,可以指定参数类型
  4. // comparing 1.0 比较集合中对象的年龄,取最大值
  5. Optional<Persons> optional = personList.stream().max(Comparator.comparing(Persons::getAge));
  6. System.out.println("comparing 1.0 : get max age " + optional.get().toString() + "\n");
  7. // comparing 2.1
  8. optional = personList.stream().max(Comparator.comparing(Persons::getName, Comparator.reverseOrder()));
  9. System.out.println("comparing 2.1 : get min name " + optional.get().toString() + "\n");
  10. // comparing 2.2
  11. optional = personList.stream().max(Comparator.comparing(Persons::getName, String::compareTo));
  12. System.out.println("comparing 2.2 : get max name " + optional.get().toString() + "\n");
  13. // comparing 2.3 该方法多了一个参数 keyComparator ,keyComparator 是创建一个自定义的比较器。示例种:通过cmmpare()方法进行学生年龄比较,
  14. optional = personList.stream().max(Comparator.comparing(Persons::getStudent, (o1, o2) -> new Student().compare(o1, o2)));
  15. System.out.println("comparing 2.3 : get max student.age " + optional.get().toString() + "\n");
  16. }
  17. /*
  18. 打印结果
  19. comparing 1.0 : get max age Persons(name=b, age=54, height=174, student=Student(age=19))
  20. comparing 2.1 : get min name Persons(name=a, age=12, height=170, student=Student(age=0))
  21. comparing 2.2 : get max name Persons(name=c, age=12, height=177, student=Student(age=0))
  22. comparing 2.3 : get max student.age Persons(name=b, age=24, height=175, student=Student(age=27))
  23. */
  24. // 升序 comparing方法的具体实现一comparingInt
  25. System.out.println("升序 : ");
  26. personList.sort(Comparator.comparingInt(Persons::getHeight));
  27. personList.forEach(System.out::println);
  28. // 降序 comparing方法的具体实现二comparingInt
  29. System.out.println("降序 : ");
  30. personList.sort(Comparator.comparingInt(Persons::getHeight).reversed());
  31. personList.forEach(System.out::println);

thenComparing方法


  1. /**
  2. * Returns a lexicographic-order comparator with another comparator.
  3. * If this {@code Comparator} considers two elements equal, i.e.
  4. * {@code compare(a, b) == 0}, {@code other} is used to determine the order.
  5. *
  6. * <p>The returned comparator is serializable if the specified comparator
  7. * is also serializable.
  8. *
  9. * @apiNote
  10. * For example, to sort a collection of {@code String} based on the length
  11. * and then case-insensitive natural ordering, the comparator can be
  12. * composed using following code,
  13. *
  14. *
  15. <pre>{@code
  16. * Comparator<String> cmp = Comparator.comparingInt(String::length)
  17. * .thenComparing(String.CASE_INSENSITIVE_ORDER);
  18. * }</pre>
  19. */
  20. default Comparator<T> thenComparing(Comparator<? super T> other) {
  21. Objects.requireNonNull(other);
  22. return (Comparator<T> & Serializable) (c1, c2) -> {
  23. int res = compare(c1, c2);
  24. return (res != 0) ? res : other.compare(c1, c2);
  25. };
  26. }

从方法名称上知道这是当比较相同时的使用的一个排序规则,这里需要注意看具体实现是会先调用比较器实例中的compare方法来进行比较一轮,当结果等于0的时候才会调用other这个比较器规则进行比较。比如下面的一个DOME:

  1. List<String> strings = Arrays.asList("def", "abc", "hel", "world");
  2. strings.sort(Comparator.comparingInt(String::length).reversed() //(1)
  3. .thenComparing(String::compareToIgnoreCase) // (2)
  4. .thenComparing(Comparator.reverseOrder()) // (3)这个比较器不会被应用 因为比较器(2)已经把结果比较出来了,并且没有相等的结果,这里不会再应用(3)比较器
  5. );
  6. System.out.println(strings); // 输出[world, abc, def, hel]

当然因为有了 comparing方法的支持,所以也就有了下面两个thenComparing的重载方法

  1. default <U extends Comparable<? super U>> Comparator<T> thenComparing(
  2. Function<? super T, ? extends U> keyExtractor)
  3. {
  4. return thenComparing(comparing(keyExtractor));
  5. }
  1. default <U> Comparator<T> thenComparing(
  2. Function<? super T, ? extends U> keyExtractor,
  3. Comparator<? super U> keyComparator)
  4. {
  5. return thenComparing(comparing(keyExtractor, keyComparator));
  6. }

测试示例代码:

  1. @Test
  2. public void test2(){
  3. //根据第一个属性进行排序,如果相同则以此根据下一个thenComparing()中的属性进行排序
  4. // thenComparing 1.0
  5. System.out.println("thenComparing 1.0 : ");
  6. personList.sort(Comparator.comparing(Persons::getAge));
  7. personList.forEach(System.out::println);
  8. // thenComparing 1.1
  9. System.out.println("thenComparing 1.1 : ");
  10. personList.sort(Comparator.comparing(Persons::getAge).thenComparing(Persons::getHeight));
  11. personList.forEach(System.out::println);
  12. // thenComparing 2.0
  13. System.out.println("thenComparing 2.0 : ");
  14. personList.sort(Comparator.comparing(Persons::getAge).thenComparing(Persons::getHeight).thenComparing(Persons::getName));
  15. personList.forEach(System.out::println);
  16. }

nullsLast()/nullsFirst()


Comparator接口中有两个对null友好的比较器方法:

  1. /**
  2. * Returns a null-friendly comparator that considers {@code null} to be
  3. * less than non-null. When both are {@code null}, they are considered
  4. * equal. If both are non-null, the specified {@code Comparator} is used
  5. * to determine the order. If the specified comparator is {@code null},
  6. * then the returned comparator considers all non-null values to be equal.
  7. *
  8. * <p>The returned comparator is serializable if the specified comparator
  9. * is serializable.
  10. *
  11. * @param <T> the type of the elements to be compared
  12. * @param comparator a {@code Comparator} for comparing non-null values
  13. * @return a comparator that considers {@code null} to be less than
  14. * non-null, and compares non-null objects with the supplied
  15. * {@code Comparator}.
  16. * @since 1.8
  17. */
  18. public static <T> Comparator<T> nullsFirst(Comparator<? super T> comparator) {
  19. return new Comparators.NullComparator<>(true, comparator);
  20. }
  21. // null比非null元素都大的
  22. public static <T> Comparator<T> nullsLast(Comparator<? super T> comparator) {
  23. return new Comparators.NullComparator<>(false, comparator);
  24. }

这里是通过Comparators这个工厂类提供的NullComparator比较器实现的,看到注释有一条需要注意是如果不指定comparator参数,即传入null,那么所有的非null参数都会被视为相等。

当集合中存在null元素时,可以使用针对null友好的比较器,null元素排在集合的最前面/最后面
测试示例代码

  1. @Test
  2. public void testNulls() {
  3. // nullsLast
  4. System.out.println("nullsLast : ");
  5. personList.sort(Comparator.nullsLast(Comparator.comparing(Persons::getName)));
  6. personList.forEach(System.out::println);
  7. // nullsFirst
  8. System.out.println("nullsFirst : ");
  9. personList.sort(Comparator.nullsFirst(Comparator.comparing(Persons::getName)));
  10. personList.forEach(System.out::println);
  11. }

Comparator接口和Comparable接口

这两个接口首先要做一个简单区别。

Comparable接口

  1. * Lists (and arrays) of objects that implement this interface can be sorted
  2. * automatically by {@link Collections#sort(List) Collections.sort} (and
  3. * {@link Arrays#sort(Object[]) Arrays.sort}). Objects that implement this
  4. * interface can be used as keys in a {@linkplain SortedMap sorted map} or as
  5. * elements in a {@linkplain SortedSet sorted set}, without the need to
  6. * specify a {@linkplain Comparator comparator}.<p>

可以看到注释中说明了实现了该接口的对象,在数组中可以使用Collections.sort或者Arrays.sort方法实现排序,或者实现了该接口的对象可以作为sortedMap或者SortedSet的key。这里也提到我们不用制定一个排序或者作为key的Comparator接口。

  1. public interface Comparable<T> {
  2. /**
  3. * 省略部分注释
  4. * <p>The implementor must ensure <tt>sgn(x.compareTo(y)) ==
  5. * -sgn(y.compareTo(x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This
  6. * implies that <tt>x.compareTo(y)</tt> must throw an exception iff
  7. * <tt>y.compareTo(x)</tt> throws an exception.)
  8. */
  9. public int compareTo(T o);
  10. }

compareTo方法上的注释中提到,必须确保x.compareTo(y)y.compareTo(x)的结果是一致的,并且这也意味着当x.compartTo(y)抛出一个异常,那么y.compareTo(x)也应该去抛出一个异常,那么这里就思考到了一个关于null的设计:null.compareTo(obj)我们肯定知道会有NPE,那么你在实现compareTo方法的时候,如果obj.compareTo(null)这里也应该去抛出NPE。

这里就不去写具体的demo去演示了,这里理解为一个对象实现了Comparable接口,那么这个对象就是可比较的,并且在排序等场景下调用实现接口中的compareTo方法。

Comparator接口

Comparator接口要理解为比较器,实现其接口的类其实是比较器的一种实现,相当于一个比较的函数定义。来看下他的注释:

  1. * A comparison function, which imposes a <i>total ordering</i> on some
  2. * collection of objects. Comparators can be passed to a sort method (such
  3. * as {@link Collections#sort(List,Comparator) Collections.sort} or {@link
  4. * Arrays#sort(Object[],Comparator) Arrays.sort}) to allow precise control
  5. * over the sort order. Comparators can also be used to control the order of
  6. * certain data structures (such as {@link SortedSet sorted sets} or {@link
  7. * SortedMap sorted maps}), or to provide an ordering for collections of
  8. * objects that don't have a {@link Comparable natural ordering}.<p>

这里我们看到Arrays、Collections也提供了重载的sort方法,支持传入一个集合/数组和Comparator接口的实例。当然当前列表/数组中的对象不一定是实现了Comparable接口。

类实现了comparable接口之后,可以直接调用排序方法;而当使用comparator时,不需要类实现,具体使用时(也就是调用某些方法时)的需要类和该comparator绑定起来来实现。comparable实现内部排序,Comparator是外部排序。