Java comparator for multi-column sorting?

匆匆过客 提交于 2019-11-30 13:46:10

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

JSorter is another open source alternative for multi column sorting in Java. http://sourceforge.net/projects/jsorter/

I recently wrote a Comparator to sort multiple fields within a delimited String record. It allows you to define the delimiter, record structure and sorting rules (some of which are type-specific).

Required information is seeded to the Comparator itself, either programmatically or through an XML file.

XML is validated by a package embedded XSD file. For example, below is a tab delimited record layout with four fields (two of which are sortable):

<?xml version="1.0" encoding="ISO-8859-1"?> 
<row xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <delimiter>&#009;</delimiter>

    <column xsi:type="Decimal">
        <name>Column One</name>
    </column>

    <column xsi:type="Integer">
        <name>Column Two</name>
    </column>

    <column xsi:type="String">
        <name>Column Three</name>
        <sortOrder>2</sortOrder>
        <trim>true</trim>
        <caseSensitive>false</caseSensitive>        
        <stripAccents>true</stripAccents>
    </column>

    <column xsi:type="DateTime">
        <name>Column Four</name>
        <sortOrder>1</sortOrder>
        <ascending>true</ascending>
        <nullLowSortOrder>true</nullLowSortOrder>
        <trim>true</trim>
        <pattern>yyyy-MM-dd</pattern>
    </column>

</row>

You would then use this in java like so:

Comparator<String> comparator = new RowComparator(
              new XMLStructureReader(new File("layout.xml")));

Library can be found here:

http://sourceforge.net/projects/multicolumnrowcomparator/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!