简体   繁体   English

如何在列表中对日期进行排序?

[英]How to sort dates in a list?

I have a list of Objects . 我有一个对象列表。 The list is already sorted in order by date of the booking. 该列表已按预订日期排序。 I would like to create a new list which takes todays date as an argument and stores the last 10 booking and next 10 bookings as of todays date. 我想创建一个新的列表,以今天的日期为参数,存储截至今天的最后10个预订和接下来的10个预订。

How can this be done? 如何才能做到这一点?

transaction = session.beginTransaction();

        String hql = "FROM Booking ORDER BY scheduledDate";
        Query query = session.createQuery(hql);
List<Booking> bookingList = query.list();
Date now = new Date();
        List<Booking> lessThan = null;
        List<Booking> moreThan = null;

        for(int i =0; i<bookingList.size();i++){

            if(bookingList.get(i).getScheduledDate().compareTo(now)<0)
                lessThan.add(bookingList.get(i));

            if (bookingList.get(i).getScheduledDate().compareTo(now)>0)
                moreThan.add(bookingList.get(i));
        }

These are my getter methods. 这些是我的getter方法。

public java.util.Date getScheduledDate() {
    return scheduledDate;
}

Make a new list by taking the absolute values of the result of the difference of today's date and each of the dates in the date-list you have. 通过获取当前日期与日期列表中每个日期的差异结果的绝对值来创建新列表。

Find the position of the minimum number in the new list. 在新列表中找到最小数字的位置。 You can then get the positions of the dates you require from here. 然后,您可以从此处获取所需日期的位置。 min-pos to (min-pos + 9) will give you 10 records of next 10 bookings and (min-pos - 1) to (min-pos - 10) will give you the other set. min-pos到(min-pos + 9)会给你10个下一个10个预订的记录,(min-pos - 1)到(min-pos - 10)会给你另一个。

The result will differ a little based on whether the (today's date - date-at-min-pos) is greater than or less than zero. 结果将根据(今天的日期 - 在-min-pos的日期)是否大于或小于零而略有不同。 Then (min-pos+1) to (min-pos + 10) will give you 10 records of next 10 bookings and (min-pos) to (min-pos - 9) will give you the other set 然后(min-pos + 1)到(min-pos + 10)会给你10个下一个10个预订的记录,(min-pos)到(min-pos - 9)会给你另一个集合

You can easily do it with Java 8's stream , eg: 您可以使用Java 8的stream轻松完成,例如:

List<Booking> bookingList = query.list();
final Date today = new Date();
List<Booking> greaterThan = bookingList.stream()
        .filter(b -> b.getScheduledDate().after(today))
        .limit(10)
        .collect(Collectors.toList());

List<Booking> lessThan = bookingList.stream()
        .filter(b -> b.getScheduledDate().before(today))
        .limit(10)
        .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM