//进行排序的实体对象
package com.compile;
public class User {
String name;
String age;
public User(String name,String age){
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
//用于排序处理的实体类,可以根据具体的属性参数和降序升序参数来动态处理list集合对象的数据
package com.compile;
import java.util.Comparator;
public class ComparatorUser implements Comparator{
public int paramType;
public int sortType;
public int getSortType() {
return sortType;
}
public void setSortType(int sortType) {
this.sortType = sortType;
}
public int getParamType() {
return paramType;
}
public void setParamType(int paramType) {
this.paramType = paramType;
}
public ComparatorUser(int paramType,int sortType) {
super();
this.paramType = paramType;
this.sortType = sortType;
}
public int compare(Object obj0, Object obj1) {
User user0=(User)obj0;
User user1=(User)obj1;
int flag = 0;
String msg="";
if(paramType==0){
msg="年龄";
if(sortType==0){//升序
flag = user0.getAge().compareTo(user1.getAge());
}else if(sortType==1){//降序
flag = user1.getAge().compareTo(user0.getAge());
}
}
if(paramType==1){
msg="姓名";
if(sortType==0){//升序
flag = user0.getName().compareTo(user1.getName());
}else if(sortType==1){//降序
flag = user1.getName().compareTo(user0.getName());
}
}
System.out.println("根据:"+msg+"----排序");
return flag;
}
}
//测试方法
package com.compile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestUserSort {
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(0,1);
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());
}
}
}