Thursday, September 24, 2009

Sorting Collections in Java

Now this is a pretty basic requirement that Java developers often face. You may want to sort an array of Strings or an List of Complex user defined object based on any field of that object. Java provides you with several options for this purpose that we are going to explore.

Sorting An Array of Pre-defined Data Types

To sort simple objects like String, Integer or primitive Data types, you can simply use build-in functions like:

  • Collections.sort( );
  • Arrays.sort( );

Sorting List of Objects – Comparable Vs Comparator

A more practical example would be to sort a User-defined Object on any field of that Object. Suppose we have a Person class that looks like the following:

Personjava

Now, we want to sort an ArrayList of Persons based on their name, we have 2 options:

Have Person Class Implement Comparable Interface

Have your person class implement the Comparable Interface, which makes you implement compareTo(..) method, which is actually used by build-in sorting methods to sort Persons. This method looks like following and compares two person objects, which determines which Person should come first in the sorted order.

PersonComparable

This method compareTo(..) is used to Compare two Person Objects based on their name. It returns an integer value: 0 if both of them are equal, positive value if the first object comes before the second one, and negative value if first object comes after the second one.

Now call sort() on it as follows,

sortingPersons

where persons is an ArrayList of Persons. As already said, the sort() method internally uses compareTo(..) method to sort these Person Objects

Create a Separate Class (Comparator Class) implementing Comparator Interface

A better way to sort these Persons is to create a separate comparator class as shown below.

comparatorPerson

Here we have created a static inner class which is used in sort() method as follows:

personComparator

Comparable Vs Comparator

I call it a better way as you can now sort your Person class on different fields: Suppose now you want to sort Persons based on their Age, then all you need to do is create a new Comparator class based on age and call sort method with this comparator.

Note:

The code shown above is compatible with Java 1.5 and above. The non-generic functions for Comparable and Comparators looks a bit different but inherently serve the same purpose.

2 comments:

Arun Gupta said...

Agraj,

I bumped into this blog while searching for sorting lists, thanks for authoring this. Hope you are doing well :-)

Agraj said...

Hi Arun, Thanks for appreciating. Me good. Hope you are also doing fine... :-)
So hows life with Oracle ? How different is it being with Sun ?