也谈Java汉字按照拼音排序
最近项目上使用到汉字排序的问题,网上搜索了一下后普遍使用下面的方法比较。
@Testpublic void test_sort_pinyin() {Collator cmp = Collator.getInstance(java.util.Locale.CHINA);String[] arr = { "张三", "李四", "王五", "赵六", "JAVA", "123", "$%$#", "哈哈A","1哈哈A", "1哈哈b", "1哈哈a", "哈哈", "哈", "怡情" };List<String> list = Arrays.asList(arr);Arrays.sort(arr, cmp);System.out.println(list);}
import java.util.Comparator;import net.sourceforge.pinyin4j.PinyinHelper;/** * 汉字按照拼音排序的比较器 * @author KennyLee 2009-2-23 10:08:59 * */public class PinyinComparator implements Comparator<Object> {public int compare(Object o1, Object o2) {char c1 = ((String) o1).charAt(0);char c2 = ((String) o2).charAt(0);return concatPinyinStringArray(PinyinHelper.toHanyuPinyinStringArray(c1)).compareTo(concatPinyinStringArray(PinyinHelper.toHanyuPinyinStringArray(c2)));}private String concatPinyinStringArray(String[] pinyinArray) {StringBuffer pinyinSbf = new StringBuffer();if ((pinyinArray != null) && (pinyinArray.length > 0)) {for (int i = 0; i < pinyinArray.length; i++) {pinyinSbf.append(pinyinArray[i]);}}return pinyinSbf.toString();}}
@Testpublic void test_sort_pinyin2() {String[] arr = { "张三", "李四", "王五", "赵六", "JAVA", "123", "$%$#", "哈哈A","1哈哈A", "1哈哈b", "1哈哈a", "哈哈", "哈", "怡情" };List<String> list = Arrays.asList(arr);Arrays.sort(arr, new PinyinComparator());System.out.println(list);}