16

I have a list of objects ordered by a date parameter and want to reorder them by category parameter, but keeping the date order within the category.

Is something like this enough, or do I have to implement a comparator that takes on account the date for objects of the same category?

// sort the list by category asc(, date asc )
Collections.sort((List<Object>)entries, new Comparator<Object>() {

    @Override public int compare(Object elementA, Object elementB) {
        return elementA.category.compareTo(elementB.category); // what happens when elementA.category.equals(elementB.category)?
    }

});
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
NotGaeL
  • 8,344
  • 5
  • 40
  • 70
  • 1
    IMO if you need to sort by something, sort by something--don't leave it to chance, or the result of another sort. – Dave Newton Feb 19 '15 at 18:18
  • `Collections.sort` uses `Arrays.sort` behind the scenes, which does a merge sort. The code of that merge sort is [here](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Arrays.java#Arrays.mergeSort%28java.lang.Object%5B%5D%2Cjava.lang.Object%5B%5D%2Cint%2Cint%2Cint%29). – Voicu Feb 19 '15 at 18:21
  • 2
    It's always a good idea to read the Javadoc for a method, before asking on Stack Overflow exactly what the method does. In this particular case, the Javadoc answers your question very, very clearly. – Dawood ibn Kareem Feb 19 '15 at 18:29
  • 1
    Thanks for clearing it out! I actually found `This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.` on the docs while writing the question, but I was unsure if `equal elements` was refering to the result of the comparator or actually comparing the elements (instead of their properties) with `objectA.equals(objectB)`, which I knew it most probably wasn't going to be the case, but I wanted to be 100% sure (I even did a test to check it out but I wanted some ratification in case it was just coincidence, I guess that was a little paranoid). – NotGaeL Feb 19 '15 at 19:21

1 Answers1

23

The code in your question will do what you need it to, since Collections.sort() does preserve the order of equal elements.

From the documentation:

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

In other words, if the entries are ordered by date before the sort(), they will stay ordered by date within each category after the sort().

If you don't want to rely on the original ordering, you can easily extend your comparator to first compare the categories and then break ties using the dates.

NPE
  • 486,780
  • 108
  • 951
  • 1,012