Comparator详解

Comparator是一个专用的比较器,当这个对象不支持自比较或者自比较函数不能满足要求时,可写一个比较器来完成两个对象之间大小的比较。Comparator体现了一种策略模式(strategy design pattern),就是不改变对象自身,而用一个策略对象(strategy object)来改变它的行为。

比如我有一组数字需要对其进行正序排序,java8之前我们通常的做法是:

 Integer [] values = new Integer[]{1,0,3,5,7,8,5,4,3,7,9,56,3,23};
Arrays.sort(values, new Comparator<Integer>() {
            @Override
            public int compare(Integer value1, Integer value2) {
                return value1- value2;
            }
        });

而在java8中,由于新增lambda表达式,我们可以很简洁的使用如下的方式:

Integer [] values = new Integer[]{1,0,3,5,7,8,5,4,3,7,9,56,3,23};
 Arrays.sort(values, (x,y) -> x-y);

可以看到代码量更加简洁更加清晰,jdk甚至为了排序做了一些定制的方法,比如上面的代码可以写成如下的方式,更加让人容易理解:

Integer [] values = new Integer[]{1,0,3,5,7,8,5,4,3,7,9,56,3,23};
Arrays.sort(values, Comparator.comparingInt(x -> x));

由于本文不会专门讲解java8中关于lambda表达式的内容,只讲解主题相关的Comparator的使用,如果想了解更多关于lambda表达式的内容,还请参考其他文章.

Comparator使用

Comparator是一个函数式接口,只有一个 int compare(T o1, T o2);方法供外部使用,但是java8在其基础上定制了许多default方法,这些default方法,开箱即用,下面我们就看看有哪些default方法以及如何使用.

reversed()

default Comparator<T> reversed() {
        return Collections.reverseOrder(this);
    }

顾名思义,可以知道这个方法是用来生成一个逆序器,比如我们开始需要得到一个正序的排序序列,然后又想得到一个反转的排序序列,就可以使用该方法,比如:

Integer [] values = new Integer[]{1,0,3,5,7,8,5,4,3,7,9,56,3,23};
Comparator<Integer> comparator = Comparator.comparingInt(x -> x);
Arrays.sort(values, comparator);
System.out.println(JSON.toJSONString(values));
Arrays.sort(values, comparator.reversed());
System.out.println(JSON.toJSONString(values));

结果如下:

[0,1,3,3,3,4,5,5,7,7,8,9,23,56]
[56,23,9,8,7,7,5,5,4,3,3,3,1,0]

可以看到,先得到正序排序的序列,然后调用comparator.reversed(),我们将内容进行反转

thenComparing(Comparator<? super T> other)

default Comparator<T> thenComparing(Comparator<? super T> other) {
        Objects.requireNonNull(other);
        return (Comparator<T> & Serializable) (c1, c2) -> {
            int res = compare(c1, c2);
            return (res != 0) ? res : other.compare(c1, c2);
        };
    }

顾名思义,该方法是在原有的比较器上再加入一个比较器,比如我们有一些用户,在对其进行排序的时候,我们首先对他的名字长度进行排序,然后再对他的年龄进行排序,如下:

person类

class Person{
        private int age;
        private String name;
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Person(int age, String name) {
            this.age = age;
            this.name = name;
        }
        @Override
        public String toString() {
            return "Person{" +
                    "age=" + age +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

测试代码:

Person [] persons = new Person[]{
                new Person(22,"zhangsan"),
                new Person(23,"lisi"),
                new Person(23,"wangwu"),
                new Person(22,"wangwu"),
                new Person(22,"lisi"),
                new Person(23,"zhangsan")
        };
        System.out.println(JSON.toJSONString(persons));
        Comparator<Person> comparator = Comparator.comparingInt(x -> x.name.length());
        Arrays.sort(persons,comparator);
        System.out.println(JSON.toJSONString(persons));
        comparator = comparator.thenComparing(Comparator.comparingInt(x->x.age));
        Arrays.sort(persons,comparator);
        System.out.println(JSON.toJSONString(persons));

结果如下:

[{"age":22,"name":"zhangsan"},{"age":23,"name":"lisi"},{"age":23,"name":"wangwu"},{"age":22,"name":"wangwu"},{"age":22,"name":"lisi"},{"age":23,"name":"zhangsan"}]
[{"age":23,"name":"lisi"},{"age":22,"name":"lisi"},{"age":23,"name":"wangwu"},{"age":22,"name":"wangwu"},{"age":22,"name":"zhangsan"},{"age":23,"name":"zhangsan"}]
[{"age":22,"name":"lisi"},{"age":23,"name":"lisi"},{"age":22,"name":"wangwu"},{"age":23,"name":"wangwu"},{"age":22,"name":"zhangsan"},{"age":23,"name":"zhangsan"}]

上述代码甚至可以简化成如下:

Comparator<Person> comparator = Comparator.comparing(Person::getName).thenComparing(Person::getAge);

default <U> Comparator<T> thenComparing(
Function<? super T, ? extends U> keyExtractor,
Comparator<? super U> keyComparator)

default <U> Comparator<T> thenComparing(
            Function<? super T, ? extends U> keyExtractor,
            Comparator<? super U> keyComparator)
    {
        return thenComparing(comparing(keyExtractor, keyComparator));
    }

待补充

推荐阅读更多精彩内容