Java List sort collections.sort () sort list

Source: Internet
Author: User

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

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.