簡體   English   中英

如何使用比較器按降序排序日期

[英]how to sort date in descending order using comparator

我有一個帶有getter setter和testBean的bean對象testBean 。我正在從數據庫中檢索結果並將其存儲在TreeMap

Map的輸出將如下所示:

{Student1 = [testBean[Dept=Science,ID=12,grade=A,Date=12-Jan-2013]]
            [testBean[Dept=Science,ID=12,grade=B,Date=14-Mar-2013]]

{Student2 = [testBean[Dept=Science,ID=02,grade=A,Date=12-Jan-2013]]
            [testBean[Dept=Science,ID=02,grade=A,Date=14-Mar-2013]]

我需要按降序排列輸出,以便最新的日期出現。 所以我使用比較器來對日期進行排序:

public int DateCompare(Object studentObj, Object anotherStudentObj) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
    String value = ((testBean) studentObj).getDateTmTrans();
    String value1 = ((testBean) anotherStudentObj).getDateTmTrans();
    int retVal = 0;

    try {

        Date firstDate = dateFormat.parse(value);
        Date secondDate = dateFormat.parse(value1);     
        retVal = firstDate.compareTo(secondDate);

    } catch (ParseException e) {
        e.printStackTrace();
    }       
    return 0;
}

但我無法按降序排列日期。 是否有任何解決方案可以獲得所需的輸出?

歡迎任何建議

提前致謝

但我無法按降序排列日期。

兩個簡單的選擇:

  • 您可以使用secondDate.compareTo(firstDate)反轉您的比較。 (我假設在您的真實代碼中,您實際上正在返回retVal ;它會在您發布的代碼中被忽略。)
  • 調用Collections.reverseOrder(Comparator)創建一個比較原始逆序的比較器。

相反,比較firstDatesecondDate ,比較secondDatefirstDate

retVal = secondDate.compareTo(firstDate);

並且不要忘記返回retVal而不是0 ;)

你可以在比較器的構造函數中添加一個布爾參數,例如boolean descending ,然后執行以下操作:

retVal = (descending ? -1 : 1) * firstDate.compareTo(secondDate);

在這里,如果您通過將true作為“降序”參數傳遞來創建比較器,它將翻轉符號,保持0不受影響,並且實際上您最終會得到一個可輕松配置的比較器,以幫助您按升序/降序排序日期訂購。

你可以試試這個:

static final Comparator<All_Request_data_dto> byDate
    = new Comparator<All_Request_data_dto>() {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");

    public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
        Date d1 = null;
        Date d2 = null;
        try {
            d1 = sdf.parse(ord1.lastModifiedDate);
            d2 = sdf.parse(ord2.lastModifiedDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return (d1.getTime() > d2.getTime() ? -1 : 1);     //descending
    //  return (d1.getTime() > d2.getTime() ? 1 : -1);     //ascending
    }
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM