3.10. Comparing Beans
Problem
You need to sort or compare beans by a bean property.
Solution
Use
BeanComparator
to compare two beans using a bean property, which can be simple,
nested, indexed, or mapped. BeanComparator
obtains
the value of the same bean property from two objects and, by default,
compares the properties with a
ComparableComparator
. The following example sorts
a list of Country
objects using a
BeanComparator
and the default
ComparableComparator
:
import java.util.*; import org.apache.commons.beanutils.BeanComparator; Country country1 = new Country( ); country1.setName( "India" ); Country country2 = new Country( ); country2.setName( "Pakistan" ); Country country3 = new Country( ); country3.setName( "Afghanistan" ); // Create a List of Country objects Country[] countryArray = new Country[] { country1, country2, country3 }; List countryList = Arrays.asList( countryArray );// Sort countries by name
Comparator nameCompare = new BeanComparator( "name" );
Collections.sort( countryList, nameCompare );
System.out.println( "Sorted Countries:" ); Iterator countryIterator = countryList.iterator( ); while( countryIterator.hasNext( ) ) { Country country = (Country) countryIterator.next( ); System.out.println( "\tCountry: " + country.getName( ) ); }
This code creates three Country
objects with
different names, places the Country
objects into a
list, and sorts this list with a BeanComparator
configured to compare by the bean property name
. This code executes and prints the sorted ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.