You can first take a look at this static method public static <T> void sort(List<T> list, Comparator<? super T> c)
1. Define a model first:
The code copy is as follows:
package model;
/**
* User.java
*
* @author Liang WP March 3, 2014
*/
public class User
{
private String userName;
private int userAge;
public User()
{
}
public User(String userName, int userAge)
{
this.userName = userName;
this.userAge = userAge;
}
public String getUserName()
{
return userName;
}
public void setUserName(String userName)
{
this.userName = userName;
}
public int getUserAge()
{
return userAge;
}
public void setUserAge(int userAge)
{
this.userAge = userAge;
}
}
2. Then define a comparator, implement the java.util.Comparator interface, and write comparison rules in the compare() method:
The code copy is as follows:
package util;
import java.util.Comparator;
import model.User;
/**
* ComparatorUser.java
*
* @author Liang WP March 3, 2014
*/
public class ComparatorUser implements Comparator<User>
{
@Override
public int compare(User arg0, User arg1)
{
// Compare the names first
int flag = arg0.getUserName().compareTo(arg1.getUserName());
// If the name is the same, it will be compared with age
if (flag == 0)
{
return arg0.getUserAge() - arg1.getUserAge();
}
return flag;
}
}
3. When sorting, use the sort(List list, Comparator c) method in java.util.Collections:
The code copy is as follows:
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import util.ComparatorUser;
import model.User;
/**
* TestApp.java
*
* @author Liang Weiping March 3, 2014
*/
public class TestApp
{
public static void main(String[] arg0)
{
List<User> userList = new ArrayList<User>();
// Insert data
userList.add(new User("A", 15));
userList.add(new User("B", 14));
userList.add(new User("A", 14));
// Sort
Collections.sort(userList, new ComparatorUser());
// Print the result
for (User u : userList)
{
System.out.println(u.getUserName() + " " + u.getUserAge());
}
}
}
4. Operation results:
The code copy is as follows:
A 14
A 15
B 14