Sorting your Beans

November 3rd, 2009 by David Casleton Leave a reply »

Need to sort a list of custom objects?   Instead of coding up a custom implementation of your favorite sorting algorithm, you can simply use the tools provided in the Collections class (Collections framework) paired with the BeanComparator class (Apache project).

Simple example: you have a List of Person objects and you want to sort via the lastName.

List<Person> people = ... ;
Collections.sort(people, new BeanComparator("lastName"));

Sorting complete!  And good news, the sort method guarantees n log(n) performance through a special implementation of merge sort.

Is your custom object more complicated?  Perhaps you encapsulated all the name information (first, middle, last) in another object within Person, called Name.

Collections.sort(people, new BeanComparator("name.lastName"));

Want the list sorted in descending order?

Collections.sort(people, new BeanComparator("name.lastName"));
Collections.reverse(people);

There are some other great utilities in there including methods to find the min and max based on a given field, as above.  You could even search for a single element using their binary search implementation, but beware: your list should already be sorted!

Advertisement

3 comments

  1. sud says:

    Does the nested property capability work if you only have a getter for the parent and not an instance variable.

    ie if Person was …
    public Name getName() { ..}

    instead of
    private Name name;
    public Name getName() { ..}

  2. Paris Holley says:

    You should probably mention that BeanComparator is apart of the apache project, not the Collections API :)

  3. David Casleton says:

    Yeah, sorry. The BeanComparator is from Apache.

    It appears that the nesting works as long as there’s a getter method, similar to calling it through EL.

Leave a Reply