Java List 按某字段排序

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/Eileen_crystal/article/details/77854866

Java List 按某字段排序

代碼支持:字符串(String)、日期(Date)、整型(Integer)、整形(Long)

MODEl

package com.eileen.feng.dto.stat;

/**
 * Created by Xuefeng_Wen on 2017/9/5.
 */
public class StatChargingDto{

    /** 省市code */
    private java.lang.String code;

    /** 行政區劃名稱*/
    private java.lang.String name;

    /** 數量*/
    private Long chargingStationCount;

    // END

    public StatChargingDto() {
    }

    public StatChargingDto(String code, String name, Long chargingStationCount) {
        this.code = code;
        this.name = name;
        this.chargingStationCount = chargingStationCount;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getChargingStationCount() {
        return chargingStationCount;
    }

    public void setChargingStationCount(Long chargingStationCount) {
        this.chargingStationCount = chargingStationCount;
    }
}

UTIL

package com.eileen.feng.util;

import com.eileen.feng.dto.stat.StatChargingDto;

import java.util.*;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

/**
 * 這是一個自定義排序的類,專門針對列表(List)中的數據進行排序;可按指定方法進行。
 * 目前實現對字符串(String)、日期(Date)、整型(Integer)、整形(Long) 等四種對象進行排序。
 * @author Xuefeng_Wen
 *
 * @param <E>
 */
public class MySortList<E> {

    /**
     * 對列表中的數據按指定字段進行排序。要求類必須有相關的方法返回字符串、整型、日期等值以進行比較。
     * @param list
     * @param method
     * @param reverseFlag
     */
    public void sortByMethod(List<E> list, final String method, final boolean reverseFlag) {
        Collections.sort(list, new Comparator<Object>() {
            @SuppressWarnings("unchecked")
            public int compare(Object arg1, Object arg2) {
                int result = 0;
                try {
                    Method m1 = ((E) arg1).getClass().getMethod(method, null);
                    Method m2 = ((E) arg2).getClass().getMethod(method, null);
                    Object obj1 = m1.invoke(((E)arg1), null);
                    Object obj2 = m2.invoke(((E)arg2), null);
                    if(obj1 instanceof String) {
                        // 字符串
                        result = obj1.toString().compareTo(obj2.toString());
                    }else if(obj1 instanceof Date) {
                        // 日期
                        long l = ((Date)obj1).getTime() - ((Date)obj2).getTime();
                        if(l > 0) {
                            result = 1;
                        }else if(l < 0) {
                            result = -1;
                        }else {
                            result = 0;
                        }
                    }else if(obj1 instanceof Integer) {
                        // 整型(Method的返回參數可以是int的,因爲JDK1.5之後,Integer與int可以自動轉換了)
                        result = (Integer)obj1 - (Integer)obj2;
                    }else if(obj1 instanceof Long) {
                        // 整型(Method的返回參數可以是Long的)
                        Long o1 = (Long)obj1;
                        Long o2 = (Long)obj2;
                        result = Integer.parseInt(o1.toString()) - Integer.parseInt(o2.toString());
                    }else {
                        // 目前尚不支持的對象,直接轉換爲String,然後比較,後果未知
                        result = obj1.toString().compareTo(obj2.toString());

                        System.err.println("MySortList.sortByMethod方法接受到不可識別的對象類型,轉換爲字符串後比較返回...");
                    }

                    if (reverseFlag) {
                        // 倒序
                        result = -result;
                    }
                } catch (NoSuchMethodException nsme) {
                    nsme.printStackTrace();
                } catch (IllegalAccessException iae) {
                    iae.printStackTrace();
                } catch (InvocationTargetException ite) {
                    ite.printStackTrace();
                }

                return result;
            }
        });
    }

    // 測試函數   false 正序   true 倒敘
    public static void main(String[] args) throws Exception {
        // 生成自定義對象,然後對它按照指定字段排序
        List<StatChargingDto> listMember = new ArrayList<StatChargingDto>();
        listMember.add(new StatChargingDto("11","111",1l));
        listMember.add(new StatChargingDto("22","222",11l));
        listMember.add(new StatChargingDto("33","333",11l));
        System.out.println("Member當前順序...");
        System.out.println(listMember);

        MySortList<StatChargingDto> msList = new MySortList<StatChargingDto>();
        msList.sortByMethod(listMember, "getChargingStationCount", false);
        System.out.println("Member按字段數量排序後...");
        System.out.println(listMember);

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章