用于多列排序的Java比较器? [英] Java comparator for multi-column sorting?

查看:179
本文介绍了用于多列排序的Java比较器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何Java开源比较器用于比较多个字段的bean以进行多列排序?每列可以按升序或降序排序。

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.

对于单列排序,可以使用 org.apache.commons.beanutils.BeanComparator来实现 org.springframework.util.comparator.InvertibleComparator 一起使用。

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?

推荐答案

我几个月前写过这篇文章。

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;
    }
}

只需继承此类并覆盖doCompare-Method 。然后使用 setNext()设置链中的下一个比较器。比较器中出现的比较早,它就越重要。

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.

编辑:

还可以看到我发现的内容: http://commons.apache.org/collections/api-2.1.1/org/apache/commons/collections/comparators/ComparatorChain.html

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

这是apache commons集合库的一部分,您可以下载这里

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

这篇关于用于多列排序的Java比较器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆