4.4. Chaining Comparators
Problem
You need to sort a collection of objects by more than one property.
Solution
Use
ComparatorChain
to create a series of Comparator objects that
appear as a single Comparator. A
ComparatorChain compares two objects with each
Comparator in the chain until a
Comparator returns a nonzero value. If a
Comparator returns equality (zero), the
ComparatorChain then moves to the next
Comparator to obtain another comparison. The
following example demonstrates the use of chained
BeanComparators; if two Person
objects have the same lastName, the chain created
in this example tries to compare the objects by
firstName:
Person person1 = new Person( );
person1.setLastName( "Payne" );
person1.setFirstName( "James" );
person1.setAge( 21 );
Person person2 = new Person( );
person2.setLastName( "Payne" );
person2.setFirstName( "James" );
person2.setAge( 85 );
Person person3 = new Person( );
person3.setLastName( "Payne" );
person3.setFirstName( "Susan" );
person3.setAge( 29 );
Person[] persons = new Person[] { person1, person2, person3 };
ComparatorChain comparatorChain = new ComparatorChain( );
comparatorChain.addComparator( new BeanComparator( "lastName" ) );
comparatorChain.addComparator( new BeanComparator( "firstName" ) );
comparatorChain.addComparator( new BeanComparator( "age" ), true );
Arrays.sort( persons, comparatorChain );This example sorts an array of Person objects: by
lastName ascending, firstName
ascending, and age descending. The sorted
persons array will ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access