基于org.apache.commons.collections.comparators类,自己针对二维数组,实现多列排序。
请大家指教。
=======================================================
package comparator;
import java.io.Serializable;
import java.text.Collator;
import java.util.Comparator;
import java.util.Locale;
import org.apache.commons.collections.comparators.ComparableComparator;
/**
* @author lhy345
* @since 2010/07/10
* @mail only4dream@gmail.com
*/
public class LinesOfArrayComparator implements Comparator, Serializable {
/** The line number which comparator */
private String property;
/** The comparator */
private Comparator comparator;
public LinesOfArrayComparator(int property) {
this(property, Locale.getDefault());
}
public LinesOfArrayComparator(int property, Comparator comparator) {
this(property, comparator, Locale.getDefault());
}
public LinesOfArrayComparator(int property, Locale locale) {
this(property, ComparableComparator.getInstance(), locale);
}
public LinesOfArrayComparator(int property, Comparator comparator,
Locale locale) {
this.property = String.valueOf(property);
if (comparator != null) {
this.comparator = comparator;
} else {
this.comparator = Collator.getInstance(locale);
}
}
public int compare(Object o1, Object o2) {
int difference = -1;
Object value1 = null;
Object value2 = null;
if (property == null) {
// compare the actual objects
return comparator.compare(o1, o2);
}
if (o1 instanceof String[]) {
difference = 1;
}
if (-1 == difference) {
throw new RuntimeException("Compare type is error!");
}
try {
if (1 == difference) {
value1 = ((String[]) o1)[Integer.parseInt(property)];
value2 = ((String[]) o2)[Integer.parseInt(property)];
}
return comparator.compare(value1, value2);
} catch (Exception nsme) {
throw new RuntimeException("RuntimeException is happen!");
}
}
}
=============================测试用的类==============================
package comparator;
import java.util.Arrays;
import org.apache.commons.collections.comparators.ComparatorChain;
public class LinesComparator {
/**
* @param args
*/
public static void main(String[] args) {
String[][] arg = new String[][] {
{ "1", "2", "4" },
{ "2", "7", "3" },
{ "3", "2", "3" },
{ "2", "4", "3" },
{ "3", "4", "3" },
{ "3", "5", "3" },
{ "3", "1", "3" },
{ "2", "2", "3" },
{ "1", "2", "3" } };
ComparatorChain compChain = new ComparatorChain();
LinesOfArrayComparator customBeanComparator1 = new LinesOfArrayComparator(0);
LinesOfArrayComparator customBeanComparator2 = new LinesOfArrayComparator(1);
compChain.addComparator(customBeanComparator1);
compChain.addComparator(customBeanComparator2);
// String[][] data = changeArray(arg);
Arrays.sort(arg, compChain);
changeArray(arg);
}
private static String[][] changeArray(String[][] arg) {
String[][] ret = new String[arg[0].length][arg.length];
for (int m = 0; m < arg.length; m++) {
for (int n = 0; n < arg[0].length; n++) {
System.out.print(arg[m][n]+ " ,");
ret[n][m] = arg[m][n];
}
System.out.print("/n");
}
return ret;
}
}