汉语拼音排序比较器
下载 pinyin4j-2.5.0.jar
/** * * @author lw */import java.util.Arrays;import java.util.Comparator;import net.sourceforge.pinyin4j.PinyinHelper;/** * 汉字按照拼音排序的比较器 * @author administrator * */public class PinyinComparator implements Comparator<String> { public int compare(String str1, String str2) { int strLength = str1.length()>str2.length() ? str2.length() : str1.length(); for(int i = 0; i < strLength; i++) { String s1 = concatPinyinArray(PinyinHelper.toHanyuPinyinStringArray(str1.charAt(i))); String s2 = concatPinyinArray(PinyinHelper.toHanyuPinyinStringArray(str2.charAt(i))); int result = s1.compareTo(s2); if(result != 0) { return result; } } return str1.length()<str2.length() ? -1 : 1; } private String concatPinyinArray(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(); } public static void main(String[] args) { String[] arrs = { "张三", "张三si", "张高", "赵六", "JAVA", "123", "$%$#", "哈哈A", "怡情"}; Arrays.sort(arrs, new PinyinComparator()); for(String s : arrs) { System.out.println(s); } }}