1

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.

Ali Ihsan
  • 609
  • 3
  • 9
  • It's not a duplicate. It's trickier than just sorting by a property. – janos Nov 06 '16 at 07:26
  • And a duplicate of [*How to sort an AreayList using multiple sorting criteria*](http://stackoverflow.com/q/3704804). **Search Stack Overflow** before posting. – Basil Bourque Nov 06 '16 at 16:40

2 Answers2

1

Sort list by date, find the last item with date less than today, move items from the first to the found item to the end of the list.

kgeorgiy
  • 1,477
  • 7
  • 9
1

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)
janos
  • 120,954
  • 29
  • 226
  • 236