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