zoukankan      html  css  js  c++  java
  • java实体类集合按某字段排序方法 备份

     package simpletest;
    
    /**
     * 测试实体类
     * @author YuanReny1
     *
     */
    public class User {
        private String name;
        private String birthDay;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getBirthDay() {
            return birthDay;
        }
        public void setBirthDay(String birthDay) {
            this.birthDay = birthDay;
        }
        public User(String name, String birthDay) {
            super();
            this.name = name;
            this.birthDay = birthDay;
        }
        
    }
    package simpletest;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    
    import org.apache.commons.beanutils.BeanComparator;
    import org.apache.commons.collections.ComparatorUtils;
    import org.apache.commons.collections.comparators.ComparableComparator;
    
    public class ListSortTest {
        
        /**
         * bean的集合按照指定bean的字段排序
         * @param list 要排序的集合
         * @param filedName 字段名称
         * @param ascFlag 是否升序
         */
        public static void sort(List list, String filedName, boolean ascFlag) {
            if (list.size() == 0 || filedName.equals("")) {
                return;
            }
            Comparator<?> cmp = ComparableComparator.getInstance();
            if (ascFlag) {
                cmp = ComparatorUtils.nullLowComparator(cmp);
            } else {
                cmp = ComparatorUtils.reversedComparator(cmp);
    
            }
            Collections.sort(list, new BeanComparator(filedName, cmp));
        }
        
        static void test() {
            List<User> list = new ArrayList<>();
            list.add(new User("张三", "2020-02-01 16:00:01"));
            list.add(new User("李四", "2020-02-03 08:40:32"));
            list.add(new User("王五", "2020-02-01 09:33:32"));
            sort(list, "birthDay", false);
            for(User u : list) {
                System.out.println(u.getName() + "-> " + u.getBirthDay());
            }
        }
        
        public static void main(String[] args) {
            test();
        }
    }

    预期结果:User的集合按照birthDay降序排序

  • 相关阅读:
    jQuery 自执行函数
    IRelationalOperator空间关系接口简介
    9.2 空间拓扑运算[转]
    解决关于ArcGIS10.2服务手动启动的问题
    Multipart to single part feature
    Multipart polyline to single part lines
    VS2015 C#6.0 中的没有实现/支持的特性
    VS2015 C#6.0 中的那些新特性
    ArcGIS中各种合并要素(Union、Merge、Append、Dissolve)的异同点分析 转载
    FME2010 案例分析: 动态批量转换
  • 原文地址:https://www.cnblogs.com/xueblvip/p/13498078.html
Copyright © 2011-2022 走看看