再谈Java8 Comparator

原创
01/21 19:04
阅读数 223

1. 开始

之前在Java8 Comparator技巧谈过通过Java8中Comparator提供了一些方法,我们可以很容易构造出自定义的Comparator。

在一些常见的排序操作中非常实用,当时我以为我对Java8的Comparator那绝对是无死角的了解了,直到遇到一个要根据嵌套对象属性比较的问题。

如,我有一个User对象列表List,现在要根据User对象中的Info对象中的time属性倒序排序,示例代码如下:

private static List<User> getUserList() {
        LinkedList<User> users = new LinkedList<>();
        users.add(new User(1, 25, new Info(9)));
        users.add(new User(2, 26, new Info(8)));
        users.add(new User(3, 30, new Info(7)));
        users.add(new User(4, 28, new Info(6)));
        return users;
    }

    private static final class User {
        private Integer id;
        private int age;
        private Info info;

        public User(Integer id, int age, Info info) {
            this.id = id;
            this.age = age;
            this.info = info;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public Info getInfo() {
            return info;
        }

        public void setInfo(Info info) {
            this.info = info;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", age=" + age +
                    ", info=" + info +
                    '}';
        }
    }

    private static final class Info {
        private long time;

        public Info(long time) {
            this.time = time;
        }

        public long getTime() {
            return time;
        }

        public void setTime(long time) {
            this.time = time;
        }

        @Override
        public String toString() {
            return "Info{" +
                    "time=" + time +
                    '}';
        }
    }

先试一试看,下面哪一个是正确的:

userList.sort(Comparator.comparingLong(user -> user.getInfo().getTime()));
userList.sort(Comparator.comparingLong(user -> user.getInfo().getTime()).reversed());
userList.sort(Comparator.comparing(user -> user.getInfo().getTime()).reversed());
userList.sort(Comparator.comparingLong(User::getInfo::getTime()));

答案是都不正确,我倒不是想玩你,只是这个可以验证一下你自己对Java的lambda表达式、::和理解。

再解决这个问题之前,我们先来了解一下Java的::操作符。

2. 方法引用::

  1. 静态方法(static)引用:类名::静态方法名 如:Helper::doSomething
  2. 对象的实例方法引用:对象实例名称(或类名)::实例方法名 如:System.out::println
  3. 对象的超类方法引用:super::methodname
  4. 类构造器引用:类名::new 如:HashMap::new
  5. 数组构造器引用:类名[]::new 如:String[]:new

3. comparingLong

接下来,我们来看一下Comparator的comparingLong方法。

public static <T> Comparator<T> comparingLong(ToLongFunction<? super T> keyExtractor) {
    Objects.requireNonNull(keyExtractor);
    return (Comparator<T> & Serializable)
        (c1, c2) -> Long.compare(keyExtractor.applyAsLong(c1), keyExtractor.applyAsLong(c2));
}

其中ToLongFunction是一个函数式接口,其实可以看成lambda表达式,就是从一个T对象中获取一个long类型用于比较的函数。

@FunctionalInterface
public interface ToLongFunction<T> {
    long applyAsLong(T value);
}

注意comparingLong方法返回的是Comparator,Comparator本身也是一个函数式接口,相当于包装了一层。

所以:

userList.sort(Comparator.comparingLong(User::getInfo::getTime()));

是肯定有问题的,因为在User::getInfo已经变成一个Comparator,已经不是User对象了。

4. comparing

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor)
{
    Objects.requireNonNull(keyExtractor);
    return (Comparator<T> & Serializable)
        (c1, c2) -> keyExtractor.apply(c1).compareTo(keyExtractor.apply(c2));
}

comparing也一样,它只是把一个更加通用的Function包装成了Comparator,只是这个Function有点特殊,它的返回参数类型必须实现Comparable,否则包装不了。

当然像int这种原始类型也是可以的,会自动包装为对应的包装类。

所以:

userList.sort(Comparator.comparing(user -> user.getInfo().getTime()).reversed());

是肯定不行的,因为reversed方法不是静态方法,问题是下面这个也不行,让我比较困惑:

userList.sort(Comparator.comparing(user -> user.getInfo().getTime())::reversed);

下面这个是没有问题的,问题是默认是升序。

userList.sort(Comparator.comparingLong(user -> user.getInfo().getTime()));

难道怎的要我通过匿名内部类来实现了么?

当然,不需要,因为Comparator还有一个下面这样的方法:

public static <T, U> Comparator<T> comparing(Function<? super T, ? extends U> keyExtractor,Comparator<? super U> keyComparator)

userList.sort(Comparator.comparing(user -> user.getInfo().getTime(), Comparator.reverseOrder()));

搞定收工!

5. 完整示例代码

import org.junit.Test;

import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

public class ComparatorBTest {

    @Test
    public void comparingKey() {
        List<User> userList = getUserList();
        userList.sort(Comparator.comparing(User::getAge));
        System.out.println(userList);
    }

    @Test
    public void comparingComponent() {
        List<User> userList = getUserList();
        userList.sort(Comparator.comparing(User::getId).reversed().thenComparing(User::getAge));
        System.out.println(userList);
    }

    @Test
    public void comparing() {
        List<User> userList = getUserList();
//        userList.sort(Comparator.comparingLong(user -> user.getInfo().getTime()));
//        userList.sort(Comparator.comparingLong(user -> user.getInfo().getTime()).reversed());
//        userList.sort(Comparator.comparingLong(User::getInfo::getTime()));
//        userList.sort(Comparator.comparing(user -> user.getInfo().getTime()).reversed());
        userList.sort(Comparator.comparing(user -> user.getInfo().getTime(), Comparator.reverseOrder()));

        userList.forEach(System.out::println);
    }


    private static List<User> getUserList() {
        LinkedList<User> users = new LinkedList<>();
        users.add(new User(1, 25, new Info(9)));
        users.add(new User(2, 26, new Info(8)));
        users.add(new User(3, 30, new Info(7)));
        users.add(new User(4, 28, new Info(6)));
        return users;
    }

    private static final class User {
        private Integer id;
        private int age;
        private Info info;

        public User(Integer id, int age, Info info) {
            this.id = id;
            this.age = age;
            this.info = info;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public Info getInfo() {
            return info;
        }

        public void setInfo(Info info) {
            this.info = info;
        }

        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", age=" + age +
                    ", info=" + info +
                    '}';
        }
    }

    private static final class Info {
        private long time;

        public Info(long time) {
            this.time = time;
        }

        public long getTime() {
            return time;
        }

        public void setTime(long time) {
            this.time = time;
        }

        @Override
        public String toString() {
            return "Info{" +
                    "time=" + time +
                    '}';
        }
    }
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部