The challenge is to write a generic comparator which allows for sorting of the data based on a chosen column in either ascending or descending order when the column data type is not known upfront.

When I faced with providing the ability to sort based on columns, I realized I had to implement a comparator which based on sorting criteria can sort in either ascending or descending order. Also the data type of the columns can be different. So if I write a comparator for String, it will not work for Integer field. However as I did not know the data type of the column beforehand, I had to create something generic which worked everywhere. And my constant strive to create something simple.

Here's what I came up with:

class Comp implements Comparator{
        int rvalue;
        String cf;
        Boolean corder;

        public Comp(String compfld,Boolean order){
            cf = compfld;
            corder = order;
        }

        public int compare(Object first, Object second){
            try {
                Comparable cFirst = null, cSecond = null;
                cFirst = (Comparable) first.getClass().getField(cf).get(first);
                cSecond = (Comparable) second.getClass().getField(cf).get(second);
                return (corder.booleanValue())?cFirst.compareTo(cSecond):cSecond.compareTo(cFirst);
            } catch(Exception e) {
                throw new RuntimeException("Invalid object passed");
            }
        }
    }

This Comparator is passed on the field/column name to compare, as a string, and it fetches the column information from the object and compares with the corresponding information from the other object. Here as you can see each object instance contains all the information for a row of data. So one row maps to one object instance.