3
Collections.sort(someList, new Comparator<SomeObject>() {
            public int compare(final SomeObject object1, final SomeObject object2) {
                return (object1.getSomeDate()).compareTo(object2.getSomeDate()); 
            }}
        );

Would it give me the objects with latest dates meaning the list will contain the set of objects with latest date to oldest date?

1
  • 5
    Why not run a test to find out?
    – GaryF
    Commented Apr 9, 2010 at 10:20

6 Answers 6

10

Comparator.comparing

You can pass a method reference to Comparator.comparing.

If you want the objects to be sorted in ascending order based on the date:

someList.sort(Comparator.comparing(SomeObject::getSomeDate));

or

someList.sort(Comparator.comparing(SomeObject::getSomeDate).reversed());

for descending order.

3

To be sure you can use:

Collections.sort(someList, new Comparator<SomeObject>() {
        public int compare(final SomeObject object1, final SomeObject object2) {
            return object1.getSomeDate().after(object2.getSomeDate()) ? 1 : -1; 
        }}
);
4
  • Wouldn't this violate the Comparable contract regarding equal elements? For two equal date objects both compare(date1, date2) and compare(date2, date1) would return -1 in your implementation. Commented Apr 9, 2010 at 13:17
  • @Jörn Horstmann: theoretically it would but in practice I'm not sure that this is the case where it's worth to add one more (almost same) verification just to get the same result.
    – Roman
    Commented Apr 9, 2010 at 13:31
  • @Kevin Bourrillion: can you give more meaningful arguments?
    – Roman
    Commented Apr 9, 2010 at 20:05
  • @Roman Collections.sort, TreeMap, etc. may throw an exception if the contract is violated. From the Javadocs: Collections.sort may throw an IllegalArgumentException - (optional) if the implementation detects that the natural ordering of the list elements is found to violate the Comparable contract
    – Stefnotch
    Commented Nov 25, 2017 at 16:07
2

The default ordering of Date will put newer dates after older dates so the oldest dates would be at the beginning of your list and the newest dates at the end. Comparators have always been hard to read in my opinion so I have switched to using google's Ordering objects that implement Comparator a little cleaner. For example your Comparator could be written like this:

Ordering<SomeObject> order = Ordering.natural().onResultOf(new Function<SomeObject, Date>() {
    public Date apply(SomeObject object) {
        return object.getDate();
    }
});
Comparator<SomeObject> comparator = order; // Ordering implements Comparable so this would be legal to do
Collections.sort(someList, order);

The order Comparator that this code created would sort SomeObject objects based on their Date using the Date's natural ordering. But what makes Ordering really nice is some of extra methods change the order without having to write any more logic, for example to reverse the order of dates to be newest to oldest you just have to add a call to reverse():

Ordering<SomeObject> order = Ordering.natural().reverse().onResultOf(new Function<SomeObject, Date>() {
    public Date apply(SomeObject object) {
        return object.getDate();
    }
});
2
  • the only thing I don't understand here is why you have the 'comparator' temporary variable. You don't use it or need it. Note that as well as Collections.sort(someList, order) you could alternatively do List<SomeObject> newList = order.sortedCopy(someList). Commented Apr 9, 2010 at 19:35
  • That was mostly done clearly show that Ordering<SomeObject> implemented Comparator<SomeObject>, but thanks for the comment about sortedCopy I hadnt noticed that method before.
    – Yanamon
    Commented Apr 11, 2010 at 2:38
1

This is old but may be someone can use it. It may be sorted using java8 as follows:

  someList.sort(Comparator.comparing(listMember::dateProducingMethod))
0

By using lambdaj you could achieve the same result in an easier and more readable way as it follows:

sort(someList, on(SomeObject.class).getSomeDate());

Far better than writing an obscure inner class, isn't it?

0

Try this:

  List<Date> list=new ArrayList<Date>();
  //add some dates to list
  Collections.sort(list, new Comparator<Date>() {
      public int compare(final Date object1, final Date object2) {
          return Long.compare(object1.getTime(),object2.getTime());
      }}
  );

Date.getTime() "converts" the date to a long, which is easier to compare and sort.

Anyway behind the curtain Longs are compared with this:

public static int compare(long x, long y) {
    return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

If you want to invert the sort, just multiply by -1 like this:

  List<Date> list=new ArrayList<Date>();
  //add some dates to list
  Collections.sort(list, new Comparator<Date>() {
      public int compare(final Date object1, final Date object2) {
          return Long.compare(object1.getTime(),object2.getTime())*-1;
      }}
  );

Not the answer you're looking for? Browse other questions tagged or ask your own question.