Tip – Get to Know Collections.sort

Get to know Collections.sort and how to implement custom Comparators.  This might seem like a bore, but if you ever attempt to sort something by yourself or to figure out how to return the indices of something else that has been sorted, then you will thank me.  

For example, imagine that you have an ArrayList that contains lists of an object we will call WorkSet.  Now imagine that each WorkSet item contains a Date that can be grabbed with getDate().  Imagine that you want to sort the ArrayList of lists by the Date of the last element within each of the lists.  Sound like a nightmare?  Not with a custom comparator, it is actually quite simple.

Define a custom Comparator and Override its compare method such that it accepts two instance of List<WorkSet> and returns the following values:

  • Return a negative value if object1 is smaller than object2
  • Return 0 (zero) if object1 is equal to object2.
  • Return a positive value if object1 is larger than object2.

Then call Collections.sort, passing in the ArrayList of List<WorkSet> and the custom comparator.

ArrayList<List<WorkSet>> arrayListArrayListWorksets = new ArrayList<List<WorkSet>>();
...

// Sort the List<WorkSet> by the date of the last value in each list
Comparator<List<WorkSet>> comparator_workset = new Comparator<List<WorkSet>>() {
 @Override
 public int compare(List<WorkSet> set1, List<WorkSet> set2) {
 int last1 = set1.size() - 1;
 int last2 = set2.size() - 1;
 return -1 * set1.get(last1).getDate().compareTo(set2.get(last2).getDate());
 }

};

Collections.sort(arrayListArrayListWorksets, comparator_workset);

Leave a comment