X
Business

Implement the Comparable interface with BeanComparator

If you want to take advantage of sorting methods in Java, you'll need to implement the Comparable interface.
Written by David Petersheim, Contributor
If you want to take advantage of sorting methods in Java, you'll need to implement the Comparable interface.

public interface java.lang.Comparable {
    public int compareTo(Object o);
}

The Comparable interface is simple because it only has one method; however, implementing the compareTo method can become tedious if you need to sort your object by multiple properties (especially if your class has a lot of these properties). If you need to implement Comparable, let BeanUtils do the work for you. BeanComparator is a class in the BeanUtils API that allows you to easily sort your Bean classes by any property you choose.

Below is a complete working example. Be sure to notice the code that creates the BeanComparator and the implementation of the compareTo method. The main method is supplied simply to build a list of objects to sort and display the before-and-after results of sorting.

When you create the BeanComparator object, you must tell it which property of your class will be used to sort. In the supplied example, the name property was chosen.

private BeanComparator comparator = new BeanComparator("name");

The line that does all the work is in the compareTo method.

return this.comparator.compare(this, o);

The compare method of the BeanComparator takes the two arguments to be compared and returns an integer representing less than, equal to, or greater than.

If you were implementing a comparator to compare properties dynamically (e.g., think of sorting rows in a table on a Web page based on which column the customer selects), then you could put off building your comparator until you knew which property had been selected for sorting. This is where BeanComparator really shines. The massive amounts of code you'd normally write to implement this behavior are reduced to a few lines when you use BeanComparator.

import java.util.Collections;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Random;
import org.apache.commons.beanutils.BeanComparator;
public class CompareTipA implements Comparable {
    private int id;
    private String name;
    private BeanComparator comparator = new BeanComparator("name");
    private static String []names =
            {"John", "Malik", "Susan", "Chaquitha", "Cheryl", "Mike", "Henri",
            "Jason", "Eric", "Jason", "Vivek", "Jakob", "Revathy", "Jim",
 "Sterling",
            "Dana", "Jill", "Amrita", "Heather", "Jack", "David", "Bethany",
 "Karol",
            "Phil", "Margaret", "Betty", "Perry", "Scott", "Dexter"};
    public static void main(String []args) {
        int count = 30;
        Random rand = new Random(System.currentTimeMillis());
        ArrayList list = new ArrayList();
        for (int i = 0; i < count; i++) {
            int id = rand.nextInt(10000);
            String name = names[rand.nextInt((names.length))];
            list.add(new CompareTipA(id, name));
        }
        System.out.println("unsorted:");
        Iterator tor = list.iterator();
        while (tor.hasNext()) {
            CompareTipA ct = (CompareTipA) tor.next();
            System.out.println(ct);
        }
        Collections.sort(list);
        System.out.println("\nsorted:");
        tor = list.iterator();
        while (tor.hasNext()) {
            CompareTipA ct = (CompareTipA) tor.next();
            System.out.println(ct);
        }
    }
    public CompareTipA(int id, String name) {
        this.id = id;
        this.name = name;
    }
    public int getId() {
        return this.id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int compareTo(Object o) {
        return this.comparator.compare(this, o);
    }
    public String toString() {
        return "[id=" + this.id + ",name=" + this.name + "]";
    }
}

BeanComparator is part of commons-beanutils, which depends on commons-logging and commons-collections. You can find out more at the Apache Jakarta site. Check out the documentation and see what else you can find hiding in the commons-beanutils API.

David Petersheim is the Director of Application Development with Genscape, Inc. He designs and develops server-side applications to acquire and process real-time energy data.

Editorial standards