Ali Ihsan Ali Ihsan - 1 month ago 15
Java Question

java sort list by current date then by date comparison

I have an ArrayList of objects

Foo(int id, Date date)
.

How would i go about sorting this ArrayList to look something like below

id = 3, date = 07 Nov 2016
id = 2, date = 08 Nov 2016
id = 5, date = 30 Nov 2016
id = 1, date = 05 Nov 2016
id = 4, date = 04 Nov 2016


The top three objects are in the future sorted by closest (to the present) first, bottom two are in the past sorted by closest (to the present) first.

Answer

To sort by multiple criteria, you need a composite comparator:

Collections.sort(dates, (d1, d2) -> {
    if (d1.after(now) && d2.after(now)) {
        return d1.compareTo(d2);
    }
    if (d1.before(now) && d2.before(now)) {
        return -d1.compareTo(d2);
    }
    return -d1.compareTo(d2);
});

That is:

  • If both dates are after now, sort them in normal order (increasing)
  • If both dates are before now, sort them in reverse order (decreasing)
  • Otherwise (= one date is before now, the other is after), sort them in reverse order (= newer date comes first, older comes later)