Java Tips Weblog

  • Blog Stats

    • 1,205,361 hits
  • Categories

  • Archives

Group Comparator

Posted by Rob Camick on October 17, 2008

Many times a sort may need to be performed on multiple fields to get the desired result. For example, in a phone book “First Name” is sorted within “Last Name”. Using the existing Java sort utilities, Collections.sort(…) and Arrays.sort(…), this would be done by first doing a sort on the First Name and then a sort on the Last Name. Obviously it is not very efficient to perform a double sort. A better approach would be to sort on both fields in a single pass.

Since you can use any Comparator with the sort methods, the trick is to create a Comparator that can group multiple Comparators into a single Comparator. With that requirement in mind I created the GroupComparator. There is not much to discuss about this class. You must specify two Comparators to be used when you create the class. The only other method is an addComparator(…) method in case your sort is based on more than two fields.

Lets start with some simple data displayed in the following order:

With the help of the ColumnComparator class introduced in my last entry we can use the GroupComparator to Sort by descending First Name within ascending Last Name:

Vector vector = model.getDataVector();
ColumnComparator cc1 = new ColumnComparator(1);
ColumnComparator cc2 = new ColumnComparator(0, false);
GroupComparator gc = new GroupComparator(cc1, cc2);
Collections.sort(vector, gc);

Get The Code

GroupComparator.java

See Also

Column Comparator
Bean Comparator

About these ads

2 Responses to “Group Comparator”

  1. Frederik said

    Same remark, have a look at org.apache.commons.collections.comparators.ComparatorChain

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 95 other followers

%d bloggers like this: