码迷,mamicode.com
首页 > 编程语言 > 详细

java中list按照某个属性排序方法

时间:2015-08-18 13:50:50      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

public List sort(List list,final String sortName,final String direction){
        Collections.sort(list, new Comparator(){
            public int compare(Object a, Object b){
                try {
                    //根据属性名获取到field
                    Field field = a.getClass().getDeclaredField(sortName);
                    //field设置为public访问属性.
                    field.setAccessible(true);
                    
                    //获取该属性的类型
                    Class typeClass = field.getType();
                    //int排序
                    if (typeClass.equals(Integer.class)) {
                        Integer one = (Integer)field.get(a);
                        Integer two = (Integer)field.get(b);
                        
                        if ("desc".equals(direction)) {
                            return two - one;   
                        } else {
                            return one - two;
                        }
                    } else {//String排序
                        String one = (String)field.get(a);
                        String two = (String)field.get(b);
                        
                        if ("desc".equals(direction)) {
                            return two.compareTo(one);   
                        } else {
                            return one.compareTo(two);
                        }
                    }
                } catch (Exception e) {
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw, true));
                }
                return 1;
                
            }
        });
        return list;
    }

}

 

java中list按照某个属性排序方法

标签:

原文地址:http://www.cnblogs.com/lishuo/p/4738990.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!