Java 如何使用比较器按降序对日期进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24034253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 09:49:54  来源:igfitidea点击:

how to sort date in descending order using comparator

javasortingdatedatetimemap

提问by jaggs

I have a bean object testBeanwith getter setter and methods.I am retrieving the results from the database and storing it in a TreeMap

我有一个testBean带有 getter setter 和方法的 bean 对象。我正在从数据库中检索结果并将其存储在一个TreeMap

The Output of the Mapwill look like this:

的输出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]]

I need the Output to be arranged in Descending order so that the latest date comes first. So I am using a comparator to sort the date:

我需要按降序排列输出,以便最晚的日期在前。所以我使用比较器对日期进行排序:

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;
}

But I couldn't able to sort the date in descending order. Is there any solution to get the desired output?

但我无法按降序对日期进行排序。有什么解决方案可以获得所需的输出吗?

Any suggestions are welcome

欢迎任何建议

Thanks in advance

提前致谢

采纳答案by Jon Skeet

But i couldn't able to sort the date in descending order.

但我无法按降序对日期进行排序。

Two easy options:

两个简单的选择:

  • You could just reverse your comparison yourself, using secondDate.compareTo(firstDate). (I assume that in your real code you're actually returning retVal; it's ignored in your posted code.)
  • Call Collections.reverseOrder(Comparator)to create a comparator with the reverse order of the original one.
  • 您可以使用secondDate.compareTo(firstDate). (我假设在您的真实代码中您实际上正在返回retVal;它在您发布的代码中被忽略。)
  • 调用Collections.reverseOrder(Comparator)以与原始比较器的相反顺序创建一个比较器。

回答by sp00m

Instead of comparing firstDateagainst secondDate, compare secondDateagainst firstDate:

相反,比较firstDate反对secondDate,比较secondDate反对firstDate

retVal = secondDate.compareTo(firstDate);

And don't forget to return retValinstead of 0;)

并且不要忘记返回retVal而不是0;)

回答by Peter Perhá?

you could add a boolean parameter to your comparator's constructor, e.g. boolean descendingand then do this:

您可以向比较器的构造函数添加一个布尔参数,例如boolean descending,然后执行以下操作:

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

here, if you created your comparator by passing true as "descending" argument, it would flip the sign around, leave 0 unaffected, and effectively you'd end up with a comparator that is easily configurable to help you ordering dates in ascending/descending order.

在这里,如果您通过将 true 作为“降序”参数传递来创建比较器,它将翻转符号,使 0 不受影响,并且实际上您最终会得到一个可轻松配置的比较器,以帮助您按升序/降序对日期进行排序命令。

回答by Mahipal Reddy M

You can try this:

你可以试试这个:

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
    }
};