package Demo; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; //直接使用Collections来排序 public class Client { public static void main(String[] args) { // 准备要测试的数据 UserModel um1 = new UserModel("小明","001",21); UserModel um2 = new UserModel("小王","002",24); UserModel um3 = new UserModel("小李","003",25); UserModel um4 = new UserModel("小吴","004",22); UserModel um5 = new UserModel("小郑","005",20); //添加到列表中 List<UserModel> list = new ArrayList<UserModel>(); list.add(um1); list.add(um2); list.add(um3); list.add(um4); list.add(um5); System.out.println("排序前-------------"); printList(list); //实现比较器,也可以单独用一个类来实现 Comparator c = new Comparator(){ @Override public int compare(Object arg0, Object arg1) { //这里实现按照用户年龄大小来排序 UserModel temp1 = (UserModel) arg0; UserModel temp2 = (UserModel) arg1; if(temp1.getAge()>temp2.getAge())return 1; else if(temp1.getAge()<temp2.getAge())return -1; else if(temp1.getAge()==temp2.getAge())return 0; return 0; } }; //排序,主要就是依靠Comparator接口的具体实现 Collections.sort(list,c); System.out.println("排序后-------------"); printList(list); } private static void printList(List<UserModel> list) { for(UserModel um:list){ System.out.println(um); } } } package Demo; public class UserModel { private String userName,userId; private int age; public String getUserName() { return userName; } public String getUserId() { return userId; } public int getAge() { return age; } public UserModel(String userName, String userId, int age) { this.userName = userName; this.userId = userId; this.age = age; } public String toString(){ return "userName="+userName+",userId="+userId+",age="+age; } } |
|
来自: weixiaofeng01 > 《JavaDemo》