Java中Comparator進行對象排序

來源:互聯網
上載者:User

標籤: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進行對象排序

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.