Sorting objects in Java comparator

Source: Internet
Author: User

Java introduced lambda expressions and streams after 8, making the sorting method change

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"); Use the Sort method of list Words.sort (Comparator.comparingint (string::length). thencomparing (String.case_insensitive_order        )));        SYSTEM.OUT.PRINTLN (words);        Use the Collections tool class three methods equivalent to 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 ("Lili"));        Userlist.add (New User ("ABCD"));        Userlist.add (New User ("Bbde"));        Userlist.add (New User ("Cdef"));        Userlist.sort (Comparator.comparing (User::getid). thencomparing (User::getname)); System.out.println (userlist);

Output Result:

[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‘}]

Sorting objects in Java comparator

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.