Sharing Our Passion for Technology
& continuous learning
〈  Back to Blog

Sorting your Beans

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"));

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!

〈  Back to Blog