Java List sort collections.sort () sort list

Source: Internet
Author: User

A pojo example

Class User {
String name;
String age;

Public User (String name,string age) {
This.name=name;
This.age=age;
}
Public String Getage () {
return age;
}
public void Setage (String age) {
This.age = age;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
}


Specific comparison classes to implement the comparator interface

Import Java.util.Comparator;
Import java.util.List;
Import java.util.ArrayList;
Import java.util.Collections;

public class Comparatoruser implements comparator{

public int Compare (object arg0, object arg1) {
User user0= (user) arg0;
User user1= (user) arg1;

First compare the age, if the same age, then compare the name

int Flag=user0.getage (). CompareTo (User1.getage ());
if (flag==0) {
Return User0.getname (). CompareTo (User1.getname ());
}else{
return flag;
}
}

}




Test class
public class Sorttest {


public static void Main (string[] args) {
List userlist=new ArrayList ();
Userlist.add (New User ("DD", "4"));
Userlist.add (New User ("AA", "1"));
Userlist.add (New User ("ee", "5"));
Userlist.add (New User ("BB", "2"));
Userlist.add (New User ("FF", "5"));
Userlist.add (New User ("CC", "3"));
Userlist.add (New User ("GG", "6"));

Comparatoruser comparator=new Comparatoruser ();
Collections.sort(userlist, comparator);

for (int i=0;i<userlist.size (); i++) {
User user_temp= (user) userlist.get (i);
System.out.println (User_temp.getage () + "," +user_temp.getname ());
}

}
}

First Age sort, 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.