实现 Java 比较器以使用自定义排序对集合进行排序的最佳方式(就时间和空间效率而言)是什么。例如 - 我想使用以下顺序对数组进行排序 -
RWQOJMVAHBSGZXNTCIEKUPDYFL
我有以下 Java 代码可以按预期工作,但不确定是否有任何其他有效的方法可以做到这一点。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.lang.Math;
public class DiffSort {
private static String order = "RWQOJMVAHBSGZXNTCIEKUPDYFL";
// sort with comparator
public static Comparator<String> diffNaturalOrder = new Comparator<String>() {
public int compare(String v, String w) {
int diff = 0, iter = 0;
Integer index1, index2;
Integer len1 = v.length();
Integer len2 = w.length();
int len = Math.min(len1, len2); // lesser of 2 strings
for(int i=0; i<len; i++) {
index1 = order.indexOf(v.charAt(i));
index2 = order.indexOf(w.charAt(i));
// if both chars are absent in order string, use natural ordering
if(index1 == -1 && index2 == -1)
diff = new Character(v.charAt(i)).compareTo(new Character(w.charAt(i)));
else if(index1 == -1 && index2 > 0)
diff = 1;
else if(index1 > 0 && index2 == -1)
diff = -1;
else
diff = index1.compareTo(index2);
// break if we found mismatch
if(diff != 0) break;
}
// return smaller string first in sort
if(diff == 0)
diff = len1.compareTo(len2);
return diff;
}
};
// test client
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("ABCE1!4");
list.add("ABCE1!7");
list.add("!SDF");
list.add("TRWESF!");
Collections.sort(list, DiffSort.diffNaturalOrder);
// print sorted array
for(String s:list)
System.out.println(s);
}
}
/* 输出 */
ABCE1!4
ABCE1!7
特维斯!
!SDF