[转] Java中Comparator进行对象排序

Posted pekkle

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[转] Java中Comparator进行对象排序相关的知识,希望对你有一定的参考价值。

【From】 https://blog.51cto.com/thinklili/2063244

 

Java在8后引入了lambda表达式和流,使得排序方法有了变化

class User {
    int id;
    String name;
    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "User{" + "id=" + id + ", name=‘" + name + ‘\‘‘ + ‘}‘;
    }
}

List<String> words = Arrays.asList("566ggg", "ce", "ddd", "dc", "cds", "cece");
        //使用list的sort方法
        words.sort(Comparator.comparingInt(String::length).thenComparing((String.CASE_INSENSITIVE_ORDER)));
        System.out.println(words);
        //使用Collections工具类 三种方法等价
        Collections.sort(words, (s1, s2) -> Integer.compare(s1.length(), s2.length()));
        Collections.sort(words, Comparator.comparing(word -> word.length()));
        Collections.sort(words, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return Integer.compare(s1.length(), s2.length());
            }
        });
        System.out.println(words);

        List<User> userList = new ArrayList<>();
        userList.add(new User(45, "lili"));
        userList.add(new User(45, "abcd"));
        userList.add(new User(41, "bbde"));
        userList.add(new User(43, "cdef"));
        userList.sort(Comparator.comparing(User::getId).thenComparing(User::getName));
        System.out.println(userList);

 

输出结果:

[ce, dc, cds, ddd, cece, 566ggg]
[ce, dc, cds, ddd, cece, 566ggg]
[User{id=41, name=‘bbde‘}, User{id=43, name=‘cdef‘}, User{id=45, name=‘abcd‘}, User{id=45, name=‘lili‘}]

 

以上是关于[转] Java中Comparator进行对象排序的主要内容,如果未能解决你的问题,请参考以下文章

JAVA中Comparator的使用

JAVA Comparator 接口排序用法

java中的treeSet中文排序

跟王老师学集合java中Comparator的用法

Java中Comparable和Comparator比较

深入理解Arrays.sort() (转)