Using the BeanComparator class to compare two JavaBeans

In Apache Commons Beanutils there’s a handy class for comparing JavaBean objects. It is called BeanComparator and compares two different bean objects by a specified property. The property that we want to compare is sent to the BeanComparator’s constructor. This example shows a JavaBean class Car which have only one property brand. We create to objects and set the first one to BMW and the other one to Ford. Then we compare the objects using the BeanComparator by calling its method compare. Finally we print out the result.

The output from using the compare method of the BeanComparator class is negative, zero or positive based on the order of the properties. If we would to sort the values BMW and Ford, BMW would come before Ford so the value is negative. The output from the code above is:

So why -4? Simply because F is 4 letters down in the alphabet from B. I we replace the brand Ford with GMC the result would be -5.

Note that to use the BeanComparator you will also need the commons-collection and the commons-logging in your classpath.

Search for more Java info on this site here:
Custom Search

Any thoughts or questions?