O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required