java中List对象排序通用方法

来源:互联网 发布:我知谁掌管明天歌曲 编辑:程序博客网 时间:2024/05/01 11:25

在数据库中查出来的列表中,往往需要对不同的字段重新排序,一般的做法都是使用排序的字段,重新到数据库中查询。如果不到数据库查询,直接在第一次查出来的list中排序,无疑会提高系统的性能。

只要把第一次查出来的结果存放在session中,就可以对list重新排序了。一般对list排序可以使用Collections.sort(list),但如果list中包含是一个对象的话,这种方法还是行不通的。如果有下面这个对象:

//UserInfo.javapackage test;import java.text.SimpleDateFormat;public class UserInfo implements java.io.Serializable{private java.lang.Integer userId;private java.lang.String username;private java.util.Date birthDate;private java.lang.Integer age;private SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");public UserInfo(){}public UserInfo(java.lang.Integer userId,java.lang.String username,java.util.Date birthDate,java.lang.Integer age){this.userId = userId;this.username = username;this.birthDate = birthDate;this.age = age;}public void setUserId(java.lang.Integer value) {this.userId = value;}public java.lang.Integer getUserId() {return this.userId;}public void setUsername(java.lang.String value) {this.username = value;}public java.lang.String getUsername() {return this.username;}public void setBirthDate(java.util.Date value) {this.birthDate = value;}public java.util.Date getBirthDate() {return this.birthDate;}public void setBirthDatestr(String value) throws Exception{setBirthDate(formater.parse(value));}public java.lang.String getBirthDatestr() {return formater.format(getBirthDate());}public void setAge(java.lang.Integer value) {this.age = value;}public java.lang.Integer getAge() {return this.age;}public String toString() {return new StringBuffer().append(getUserId()).append("; "+getUsername()).append("; "+getBirthDatestr()).append("; "+getAge()).toString();}}


这是一个简单的数据对象,现在要对userId排序,那么用上述的方法必须要用到如下所示类似的代码:

                           

 Collections.sort(list, new Comparator() {                                public int compare(Object a, Object b) {                                  int one = ((Order)a).getUserId ();                                  int two = ((Order)b).getUserId ();                                   return one- two ;                                 }                             });   

那么要实现对UserInfo列表各字段排序,是不是每个字段都写一段如上所示的代码呢?那当然不是我们所需要的结果。写程序要写得越来越精练,不能越写越冗余。能不能写一个通用的方法呢?答案是肯定的,但首先必须能解决下面三个问题:

1  可以使用泛型;

2  能够使用通用的比较方法,比如compareTo

3  有没有类似泛型、泛型方法那样的泛方法?

1个问题可以解决,第2个问题难度也不是很大,因为Java所有的类型都继承于Object,都有一个ToString的方法,暂且可以把所有类型转换成String,然后用compareTo作比较。第3个问题日前还没有我们需要的泛方法。不过我们可以变通一下,用getMethodinvoke动态的取出方法出来。完成代码如下:

//SortList.javapackage test;import java.util.Collections;import java.util.Comparator;import java.util.List;import java.lang.reflect.Method;import java.lang.reflect.InvocationTargetException;/*** @author jardot* @version 1.0* 通用排序*/public class SortList<E>{public void Sort(List<E> list, final String method, final String sort){Collections.sort(list, new Comparator() {    public int compare(Object a, Object b) {    int ret = 0;    try{    Method m1 = ((E)a).getClass().getMethod(method, null);    Method m2 = ((E)b).getClass().getMethod(method, null);    if(sort != null && "desc".equals(sort))//倒序    ret = m2.invoke(((E)b), null).toString().compareTo(m1.invoke(((E)a), null).toString());    else//正序    ret = m1.invoke(((E)a), null).toString().compareTo(m2.invoke(((E)b), null).toString());    }catch(NoSuchMethodException ne){    System.out.println(ne);}catch(IllegalAccessException ie){System.out.println(ie);}catch(InvocationTargetException it){System.out.println(it);}    return ret;    } });}}


成功了!上面的代码没有用到具体的对象和类型,已经具有通用性了,我们用了一个泛型E,如果我们要对UserInfouserId排序的话,可以把方法名用字符串的形式用参数传进去:例如“getUserId”可以使用下面的代码测试一下:

//Test.javapackage test;import java.util.ArrayList;import java.util.List;import java.text.SimpleDateFormat;public class Test {public static void main(String[] args)throws Exception{List<UserInfo> list = new ArrayList<UserInfo>();SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");list.add(new UserInfo(3,"b",formater.parse("1980-12-01"),11));list.add(new UserInfo(1,"c",formater.parse("1980-10-01"),30));list.add(new UserInfo(2,"a",formater.parse("1973-10-01"),11));System.out.println("-------原来序列-------------------");for(UserInfo user : list){System.out.println(user.toString());}//调用排序通用类SortList<UserInfo> sortList = new SortList<UserInfo>();//按userId排序sortList.Sort(list, "getUserId", "desc");System.out.println("--------按userId倒序------------------");for(UserInfo user : list){System.out.println(user.toString());}//按username排序sortList.Sort(list, "getUsername", null);System.out.println("---------按username排序-----------------");for(UserInfo user : list){System.out.println(user.toString());}//按birthDate排序sortList.Sort(list, "getBirthDatestr", null);System.out.println("---------按birthDate排序-----------------");for(UserInfo user : list){System.out.println(user.toString());}}}


运行结果如下:

-------原来序列-------------------

3; b; 1980-12-01; 11

1; c; 1980-10-01; 30

2; a; 1973-10-01; 11

--------userId倒序------------------

3; b; 1980-12-01; 11

2; a; 1973-10-01; 11

1; c; 1980-10-01; 30

---------username排序-----------------

2; a; 1973-10-01; 11

3; b; 1980-12-01; 11

1; c; 1980-10-01; 30

---------birthDate排序-----------------

2; a; 1973-10-01; 11

1; c; 1980-10-01; 30

3; b; 1980-12-01; 11

注意:日期的排序是先通过格式转换的,再来排序的,否则将不能有正确的结果。

原创粉丝点击