中文排序问题曾经一直困扰着我,知道最近才找到方法。Collator类是中文排序的关键,官方文档是这么描述该类的:Performs locale-sensitive string comparison. A concrete subclass, RuleBasedCollator
, allows customization of the collation ordering by the use of rule sets.
好了,废话不多说了,直接上代码,相信大家一看就明白了。
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;public class Main {
/**
* @param args
*/
public static void main(String[] args) {
String[] strings={"我们","大家","你好","I love you","拼音","汉字","测试","使用"};
ArrayList<String> arrays=new ArrayList<String>();
for(int i=0;i<strings.length;i++){
arrays.add(strings[i]);
}
printList("排序前:",arrays);
Collections.sort(arrays,new Comparator<String>(){
Collator clt=Collator.getInstance();
@Override
public int compare(String o1, String o2) {
return clt.compare(o1, o2);
}
});
printList("排序后:",arrays);
}
public static void printList(String prompt,ArrayList<String> strings){
for(String s:strings){
prompt+="["+s+"],";
}
prompt=prompt.substring(0, prompt.length()-1);
System.out.println(prompt);
}
}
输出的结果是这样的:
排序前:[我们],[大家],[你好],[I love you],[拼音],[汉字],[测试],[使用]
排序后:[I love you],[测试],[大家],[汉字],[你好],[拼音],[使用],[我们]