下面是Comparator#compare函数的样子:
int compare(String o1, String o2) {
// null values always prioritized
if (o1 == o2) return 0;
if (o1 == null) return -1;
if (o2 == null) return 1;
String[] parts1 = o1.split(' '); // e.g. ["Fall", "2012"]
String[] parts2 = o2.split(' ');
// invalid data, just throw some nonsense ordering out
if (parts1.length != 2 || parts2.length != 2) {
return parts2.length - parts1.length;
}
// have winner, 4 digit years can be compared lexicographical
var yearCompare = parts[1].compareTo(parts[2]);
if (yearCompare != 0) {
return yearCompare;
}
// map term names to orderable values
String[] termWeights = { "Spring", "Summer", "Fall", "Winter" };
var term1 = termWeights.indexOf(parts1[0]);
var term2 = termWeights.indexOf(parts2[0]);
// invalid terms prioritized
if (term1 == term2) return 0;
if (term1 == -1) return -1;
if (term2 == -1) return 1;
return term2 - term1;
}
当然,我根本没有测试过这个。YMMV :)
这是另一种替代方法(基于评论):
// swap "TermName Year" to "Year TermName"
String prioritizeYear (String i) {
return i.replaceFirst("^(\\w+)\\s+(\\d+)", "$2_$1");
}
// convert "TermName" to "TermValue"
String weightTerm (String i) {
return i.replace("Spring", "1")
.replace("Summer", "2")
.replace("Fall", "3")
.replace("Winter", "4");
}
int compare(String o1, String o2) {
// null values always prioritized
if (o1 == o2) return 0;
if (o1 == null) return -1;
if (o2 == null) return 1;
String n1 = weightTerm(prioritizeYear(o1));
String n2 = weightTerm(prioritizeYear(o2));
return n1.compareTo(n2);
}
再次,YMMV。