class ArrayComparator implements Comparator<Comparable[]> {
private final int columnToSort;
private final boolean ascending;
public ArrayComparator(int columnToSort, boolean ascending) {
this.columnToSort = columnToSort;
this.ascending = ascending;
}
public int compare(Comparable[] c1, Comparable[] c2) {
int cmp = c1[columnToSort].compareTo(c2[columnToSort]);
return ascending ? cmp : -cmp;
}
}
This way you can handle any type of data in those arrays (as long as they're Comparable) and you can sort any column in ascending or descending order.
String[][] data = getData();
Arrays.sort(data, new ArrayComparator(0, true));
PS: make sure you check for ArrayIndexOutOfBounds
and others.
EDIT: The above solution would only be helpful if you are able to actually store a java.util.Date
in the first column or if your date format allows you to use plain String comparison for those values. Otherwise, you need to convert that String to a Date, and you can achieve that using a callback interface (as a general solution). Here's an enhanced version:
class ArrayComparator implements Comparator<Object[]> {
private static Converter DEFAULT_CONVERTER = new Converter() {
@Override
public Comparable convert(Object o) {
// simply assume the object is Comparable
return (Comparable) o;
}
};
private final int columnToSort;
private final boolean ascending;
private final Converter converter;
public ArrayComparator(int columnToSort, boolean ascending) {
this(columnToSort, ascending, DEFAULT_CONVERTER);
}
public ArrayComparator(int columnToSort, boolean ascending, Converter converter) {
this.columnToSort = columnToSort;
this.ascending = ascending;
this.converter = converter;
}
public int compare(Object[] o1, Object[] o2) {
Comparable c1 = converter.convert(o1[columnToSort]);
Comparable c2 = converter.convert(o2[columnToSort]);
int cmp = c1.compareTo(c2);
return ascending ? cmp : -cmp;
}
}
interface Converter {
Comparable convert(Object o);
}
class DateConverter implements Converter {
private static final DateFormat df = new SimpleDateFormat("yyyy.MM.dd hh:mm");
@Override
public Comparable convert(Object o) {
try {
return df.parse(o.toString());
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
}
And at this point, you can sort on your first column with:
Arrays.sort(data, new ArrayComparator(0, true, new DateConverter());
I skipped the checks for nulls and other error handling issues.
I agree this is starting to look like a framework already. :)
Last (hopefully) edit: I only now realize that your date format allows you to use plain String comparison. If that is the case, you don't need the "enhanced version".