码迷,mamicode.com
首页 > 编程语言 > 详细

Java中Comparator进行对象排序

时间:2018-01-20 21:34:26      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:over   return   this   .so   print   public   turn   ring   system   

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进行对象排序

标签:over   return   this   .so   print   public   turn   ring   system   

原文地址:http://blog.51cto.com/thinklili/2063244

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!