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