拼音相关的:
按拼音排序以及中文转拼音
一个拼音相关的开源库:
pinyin4j.jar
public class PinyinComparator implements Comparator {
@Override
public int compare(Object arg0, Object arg1) {
// 按照名字排序
User user0 = (User) arg0;
User user1 = (User) arg1;
String catalog0 = "";
String catalog1 = "";
if (user0 != null && user0.getUserName() != null && user0.getUserName().length() > 1)
catalog0 = PingYinUtil.converterToFirstSpell(user0.getUserName()).substring(0, 1);
if (user1 != null && user1.getUserName() != null && user1.getUserName().length() > 1)
catalog1 = PingYinUtil.converterToFirstSpell(user1.getUserName()).substring(0, 1);
int flag = catalog0.compareTo(catalog1);
return flag;
}
}
public class PingYinUtil {
/**
* 将字符串中的中文转化为拼音,其他字符不变
*
* @param inputString
* @return
*/
public static String getPingYin(String inputString) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
char[] input = inputString.trim().toCharArray();
String output = "";
try {
for (int i = 0; i < input.length; i++) {
if (java.lang.Character.toString(input[i]).matches(
"[\\u4E00-\\u9FA5]+")) {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(
input[i], format);
output += temp[0];
} else
output += java.lang.Character.toString(input[i]);
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return output;
}
/**
* 汉字转换位汉语拼音首字母,英文字符不变
*
* @param chines
* 汉字
* @return 拼音
*/
public static String converterToFirstSpell(String chines) {
String pinyinName = "";
char[] nameChar = chines.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < nameChar.length; i++) {
if (nameChar[i] > 128) {
try {
pinyinName += PinyinHelper.toHanyuPinyinStringArray(
nameChar[i], defaultFormat)[0].charAt(0);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pinyinName += nameChar[i];
}
}
return pinyinName;
}
}