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

时间:2022-09-09 02:51:20

【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'}]