Search code examples
javareflectionapache-commons

Any java APIs to sort list of objects based on passed object's field name?


I have a list of objects and I want to sort by passing the objects' field names and an order (ascending or descending). For example, my object is:

class Person{
         private String name;
         private String age;
        //getters and setters
         ..........
}


I will pass List personList, String name, and boolean isAscending to an API method for sorting the personList. I can implement this by writing an implementation class for Comparator but I want to have a generic method.

That is, if I have Address object, I should be able to sort Address object list by its field name (for ex: streetName).

Basically, I am looking for a generic sort method to sort any kind of list. Any such APIs available?


Solution

  • I'm assuming you actually have getters and setters for the properties you want to use. Using the private fields directly is probably a bad idea anyways.

    You can use BeanComparator from commons-beanutils. To sort ascending, use new BeanComparator("name"), for descending new BeanCompartor("name", Collections.reverseOrder())