import java.util.Collection;
import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;
public class TestSort {
public static void main(String[] args) {
CollatorComparator comparator = new CollatorComparator();
TreeMap map = new TreeMap(comparator);
for(int i=0; i<10; i++) {
String s = ""+(int)(Math.random()*1000);
map.put(s,s);
}
map.put("abcd","abcd");
map.put("Abc", "Abc");
map.put("bbb","bbb");
map.put("BBBB", "BBBB");
map.put("北京","北京");
map.put("中国","中国");
map.put("上海", "上海");
map.put("厦门", "厦门");
map.put("香港", "香港");
map.put("碑海", "碑海");
Collection col = map.values();
Iterator it = col.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
public class CollatorComparator implements Comparator {
Collator collator = Collator.getInstance();
public int compare(Object element1, Object element2) {
CollationKey key1 = collator.getCollationKey(element1.toString().toLowerCase());
CollationKey key2 = collator.getCollationKey(element2.toString().toLowerCase());
return key1.compareTo(key2);
}
}
现在可以看到,排序已经完全符合我们的要求了。如果要反向排序也很容易,遍历的时候倒过来,或者你写两个Comparator的实现类,正向的排序就像我们前面所写的,反向排序就将return key1.compareTo(key2);修改成return -key1.compareTo(key2);,加了个负号,这里你可以直接加个符号看看效果,结果我就不写了,肯定中国是Number One。