Entity class:
classUser {String name; String age; PublicUser (String name,string age) { This. name=name; This. age=Age ;} PublicString getage () {returnAge ;} Public voidsetage (String age) { This. Age =Age ;} PublicString GetName () {returnname;} Public voidsetName (String name) { This. Name =name;} }
The specific comparison class, implements the comparator interface:
ImportJava.util.Comparator;Importjava.util.List;Importjava.util.ArrayList;Importjava.util.Collections; Public classComparatoruserImplementscomparator{ Public intCompare (Object arg0, Object arg1) {User User0=(User) arg0; User User1=(User) arg1; //first compare the age, if the same age, then compare the name intflag=user0.getage (). CompareTo (User1.getage ()); if(flag==0){ returnuser0.getname (). CompareTo (User1.getname ()); }Else{ returnFlag; } } }
Test class:
Public classSorttest { Public Static voidMain (string[] args) {List userlist=NewArrayList (); Userlist.add (NewUser ("DD", "4")); Userlist.add (NewUser ("AA", "1")); Userlist.add (NewUser ("ee", "5")); Userlist.add (NewUser ("BB", "2")); Userlist.add (NewUser ("FF", "5")); Userlist.add (NewUser ("CC", "3")); Userlist.add (NewUser ("GG", "6")); Comparatoruser Comparator=NewComparatoruser (); Collections.sort (userlist, comparator); for(intI=0;i<userlist.size (); i++) {User user_temp=(User) userlist.get (i); System.out.println (User_temp.getage ()+","+user_temp.getname ()); } }}
First Age is sorted, and if the age is the same, sort by name.
Results:
1, AA
2, BB
3, CC
4, DD
5, EE //Note: Same as 5-year-old person, then compare name (EE,FF), then sort
5, FF
6, GG
Java List sort collections.sort () sort list