【问题标题】:Joda DateTime array sort array by date timeJoda DateTime 数组按日期时间排序数组
【发布时间】:2017-04-03 20:10:18
【问题描述】:

我有一个这样的 Joda DateTimes 数组列表:

List <DateTime> nextRemindersArray = new ArrayList<DateTime>();
nextRemindersArray.add(reminderOneDateTime);
nextRemindersArray.add(reminderTwoDateTime);
nextRemindersArray.add(reminderThreeDateTime);

我正在尝试按升序对日期进行排序,但遇到了问题:

我google了一下,找到了这个页面:

https://cmsoftwaretech.wordpress.com/2015/07/19/sort-date-with-timezone-format-using-joda-time/

我试过这样:

nextRemindersArray.sort(nextRemindersArray);

但它给了我错误:

Error:(1496, 37) error: incompatible types: List<DateTime> cannot be converted to Comparator<? super DateTime>

然后我这样尝试:

DateTimeComparator dateTimeComparator = DateTimeComparator.getInstance();
nextRemindersArray.sort(nextRemindersArray, dateTimeComparator);

还有这样的:

nextRemindersArray.sort(nextRemindersArray, new DateTimeComparator());

但都有错误。

我尝试了 Joda 时间手册,但没有太大帮助。如何对数组进行排序?

提前感谢您的帮助

【问题讨论】:

    标签: sorting datetime arraylist jodatime comparator


    【解决方案1】:

    假设我们有 SomeClass 这个方法 getCreatedDate() 返回一个 DateTime joda 对象。 对于列表,您可以有一个简单的比较器:

    private Comparator<Listing> byCreatedDate = Comparator.comparing(SomeClass::getCreatedDate);
    

    然后在你的代码中你可以调用:

     ...
     listings.sort(byCreatedDate);
     return listings;
     ...
    

    还没有测试过,但是……这个想法应该没问题。

    在 Kotlin 中,您会调用 listing.sortedBy { it.createdDate }

    【讨论】:

      【解决方案2】:

      你要找的是:

      nextRemindersArray.sort(DateTimeComparator.getInstance());
      

      但是因为DateTime 已经实现了Comparable,所以你并不需要比较器,你可以简单地使用:

      nextRemindersArray.sort(null); //uses natural sorting
      //or probably more readable
      Collections.sort(nextRemindersArray);
      

      请注意,快速查看the documentation of List::sort 会告诉您该方法只需要一个参数并且它必须是一个比较器(而不是像您的问题中那样的两个参数)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多