4.6. Fixed-Order Comparison
Problem
You need to sort a collection of objects that have a preestablished order, such as the days of the week or the order of planets in the solar system.
Solution
Use FixedOrderComparator in Jakarta Commons
Collections. When using FixedOrderComparator, you
supply an array of objects in a sorted order and the
Comparator returns comparison results based on the
order of the objects in this array. The following example uses a
fixed string array to compare different Olympic medals:
import java.util.*;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.FixedOrderComparator;
String[] medalOrder = {"tin", "bronze", "silver", "gold", "platinum"};
Comparator medalComparator = new FixedOrderComparator( medalOrder );
Comparator athleteComparator = new BeanComparator( "medal", medalComparator );
Athlete athlete1 = new Athlete( );
Athlete athlete2 = new Athlete( );
int compare = medalComparator.compare( athlete1.getMedal( ),
athlete2.getMedal( ) );In this code, a FixedOrderComparator compares two
Athletes by the value of the
medal property. The medal
property can be “tin,”
“bronze,”
“silver,”
“gold,” or
“platinum,” and a
FixedOrderComparator uses the order of the
medalOrder array to compare these values. The
medalOrder array establishes a fixed relationship
between the three medal types;
“bronze” is less than
“silver,” which is less than
“gold.”
Discussion
Use FixedOrderComparator when sorting an array or a collection ...
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