Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Comparator given the name of the property to compare

Tags:

java

compare

My problem is this; I have to order a table of data. Each row of the table is an object (lets call it TableObject) stored in a List. Each column of data is a property of the class (usually a String).

I have to do the typical ordering of data when the user clicks on any column. So I thought about changing the List to a TreeSet and implementing Comparator in my TableObject.

The problem comes when I try to reorder the TreeSet. The compare is fairly easy at first (cheeking for exceptions in parseInt have been omitted):

   public int compare(TableObject to1, TableObject to2){
        TableObject t1 = to1;
        TableObject t2 = to2;

        int result = 1;

        if(Integer.parseInt(t1.getId()) == Integer.parseInt(t2.getId())){result=0;}
        if(Integer.parseInt(t1.getId()) < Integer.parseInt(t2.getId())){result=-1;}

        return result;

    }

But when I have to reorder by the text of the data or by other dozens of data that the TableObject has I have a problem. I do not want to create dozens of compare functions, each for one. I prefer not to use a switch (or a chain of ifs) to decide how to compare the object.

Is there any way to do this in some way (like Reflexive), that doesn't imply that I will write like hundreds of lines of nearly the same code?

Thanks for all!

like image 621
Random Avatar asked Nov 09 '10 16:11

Random


People also ask

What is Comparator comparing in Java?

Java Comparator interface is used to order the objects of a user-defined class. This interface is found in java. util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).

How does Compare method of Comparator work in Java?

The compare MethodIt returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned. By overriding compare( ), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison.

What does a Comparator compare?

A comparator interface is used to order the objects of user-defined classes. A comparator object is capable of comparing two objects of the same class.

What does Comparator do in Java?

comparator,” Java Comparator compares two Java objects in a “compare(Object 01, Object 02)” format. Using configurable methods, Java Comparator can compare objects to return an integer based on a positive, equal or negative comparison.


3 Answers

Bean Comparator should work.

Using reflection the BeanComparator that will allow you to sort on any property that has a zero parameter method that returns the value of the property.

So basically you can sort on any property that has a "getter" method.

like image 161
camickr Avatar answered Sep 25 '22 09:09

camickr


What you could do is make the comparator take a String representing the name of the parameter to sort by in its constructor.

Then you could use reflection to sort by the given parameter.

The following code is very dirty. But I think it illustrates the gist of what you would need to do.

public class FieldComparator<T> implements Comparator<T> {
    String fieldName;

    public FieldComparator(String fieldName){
        this.fieldName = fieldName;
    }

    @Override
    public int compare(T o1, T o2) {
        Field toCompare = o1.getClass().getField(fieldName);
        Object v1 = toCompare.get(o1);
        Object v2 = toCompare.get(o2);
        if (v1 instanceof Comparable<?> && v2 instanceof Comparable<?>){
            Comparable c1 = (Comparable)v1;
            Comparable c2 = (Comparable)v2;
            return c1.compareTo(c2);
        }else{
            throw new Exception("Counld not compare by field");
        }
    }
}
like image 27
jjnguy Avatar answered Sep 25 '22 09:09

jjnguy


Yes, you could use the reflection API, to get the content of a field based on it's name.

See Field class and especially the Field.get method.

(I wouldn't recommend it though, as reflection is not designed for this type of task.)

like image 43
aioobe Avatar answered Sep 21 '22 09:09

aioobe