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);