Java comparator for multi-column sorting?

后端 未结 3 1829
悲哀的现实
悲哀的现实 2021-01-02 15:04

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 singl

3条回答
  •  礼貌的吻别
    2021-01-02 15:31

    I wrote this a few months ago.

    public abstract class ChainedComparator implements Comparator {
    
        private Comparator 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 getNext() {
            return next;
        }
    
        public void setNext(Comparator 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

提交回复
热议问题