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
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>	</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/