Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java comparator for multi-column sorting?

Is there any Java open-source comparator for comparing beans by multiple fields for multi-column sorting? Each column can be sorted asceding or descending.

For single-column sorting it can be achieved by using org.apache.commons.beanutils.BeanComparator together with org.springframework.util.comparator.InvertibleComparator.

I'm aware that this functionality is quite trivial to write, but what's the benefit from reinventing the wheel, if it was already written and tested?

like image 447
Danubian Sailor Avatar asked Dec 20 '12 09:12

Danubian Sailor


1 Answers

I wrote this a few months ago.

public abstract class ChainedComparator<T> implements Comparator<T> {

    private Comparator<T> next;

    @Override
    public int compare(T o1, T o2) {
        int result = doCompare(o1, o2);
        if (result == 0) {
            if (getNext() != null) {
                return getNext().compare(o1, o2);
            }
        }

        return result;
    }

    public abstract int doCompare(T o1, T o2);

    public Comparator<T> getNext() {
        return next;
    }

    public void setNext(Comparator<T> next) {
        this.next = next;
    }
}

Just inherit from this class and override the doCompare-Method. Then set a the next comparator in chain with setNext(). The earlier a comparator appears in this chain, the more "important" it is.

EDIT:

Also see what I found: http://commons.apache.org/collections/api-2.1.1/org/apache/commons/collections/comparators/ComparatorChain.html

This is part of the apache commons collection library, which you can download here

like image 162
Simon Avatar answered Sep 22 '22 05:09

Simon