Main Content

Sorting Collections of Objects in Java

Archive - Originally posted on "The Horse's Mouth" - 2009-09-25 14:21:43 - Graham Ellis

The examples that I wrote / finished yesterday ended up with a program called "Zoe" in Java, which read all the records in an access log file, created an object for each of them (which, sensibly would have been called a Hit but we called a "Zoe"), and reported on that object creation.

To finish off that example this morning, I sorted the objects (and I chose to do so based on the web server returned status codes, and where they were the same, the visiting host name), and printed them out. Th efollowing changes were made to the source code:

1. Set the class to implement "Comparable" which means that we have added a compareTo method which returns an integer (-ve, 0, +ve)

2. Called Collections.Sort on the ArrayList object (Collections.Sort is a static method of the Collection object type in java.util)

3. Provided a toString method so that we can easily display an Aileen (that's the new name of the class that I used as I wanted to leave Zoe available for delegates to look back at the intermediate stage) object.

4. Looped through our ArrayList after sorting in to output all the members in it.

In code terms:

public class Aileen implements Comparable {

Within the main program / test harness:

Collections.sort(Visits);
for (int k=0; k<Visits.size(); k++) {
  System.out.println(Visits.get(k));
  }


And new methods within the class:

public int compareTo(Object that) {
 // Can we differentiate by status?
 int newstate = this.status - ((Aileen)that).status;
 if (newstate != 0) return newstate;
 // If we can't, differentiate on host name
 return (this.Host.compareTo(((Aileen)that).Host));
 }
 
public String toString() {
 String rezult = Host + " " + /* Request + " " + */
   Time + " " + status;
 return rezult;
 }


You can sorted other ordered collection types in Java using the same mechanism, but you cannot sort any of the Hash types (Hash, HashMap, HashSet) - if you want their members in order, copy the keys to a Vector or an ArrayList.

You can also provide a Comparator object as a parameter to your call to Collections.Sort; be default, objects are sorted into what is know as their natural sort order by reference to the compareTo method, but if you provide Comparators you can have different ways of sorting them.

Full source code here.