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降序排序

posted @ 2020-08-13 18:25  薛柏梁  阅读(1086)  评论(0编辑  收藏  举报