0

Currently I am trying to sort my list by dates:

Collections.sort(unsortedDates, new Comparator<Item>() {
    public int compare(Item m1, Item m2) {
        return m1.getDate().compareTo(m2.getDate());
    }
});

But I want the list to be sorted so the anchor date will be today, the first item should be the closest date for the current date.

The date format is MM/dd.

getDate() returns a Date object.

user1940676
  • 4,348
  • 9
  • 44
  • 73

3 Answers3

5

Create today's date outside the comparator, and change your comparator to compare absolute differences for the dates it compares, like this:

final long todayTime = new Date().getTime();
Collections.sort(unsortedDates, new Comparator<Item>() {
    public int compare(Item m1, Item m2) {
        long dist1 = Math.abs(todayTime-m1.getDate().getTime());
        long dist2 = Math.abs(todayTime-m2.getDate().getTime());
        return Long.compare(dist1, dist2);
    }
});
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

Code for Java 1.5+ (autoboxing).

final long current = (new Date()).getTime();
Collections.sort(unsortedDates, new Comparator<Item>() {
    public int compare(Item m1, Item m2) {
        Long m1diff = Math.abs(m1.getDate().getTime() - current);
        Long m2diff = Math.abs(m2.getDate().getTime() - current);
        return m1diff.compareTo(m2diff);
    }
});
0

This guy has pretty much the same code as you in his answer. Maybe worth checking out.

Sort a List of Objects by Their Date

Or you have this, but it uses an ArrayList so it may not be what you're looking for, but somewhat similar.

Sort Objects in ArrayList by Date

Community
  • 1
  • 1
Watercolours
  • 393
  • 1
  • 3
  • 19