业务需求:将用户中文名字根据拼音首字母分类排序
直接上代码:
引入依赖:
<dependency><groupId>com.belerweb</groupId><artifactId>pinyin4j</artifactId><version>2.5.0</version></dependency>
创建工具类:
import cn.newi.common.util.StringUtil;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;public class PinyinUtils {/** * 将字符串中的中文转化为拼音,英文字符不变 * * @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); String output = ""; if (!StringUtil.isEmpty(inputString) && !"null".equals(inputString)) { char[] input = inputString.trim().toCharArray(); try {String notChsTmp = "";for (int i = 0; i < input.length; i++) {if (java.lang.Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) {if (!StringUtil.isEmpty(notChsTmp)){output += notChsTmp;output += " "; notChsTmp = "";}String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format); output += temp[0]; if (i < input.length - 1){output += " "; }} else {notChsTmp += java.lang.Character.toString(input[i]); }}//循环外面如果最后一个不是中文,最后补加上非中文字符串if (!StringUtil.isEmpty(notChsTmp)){output += notChsTmp;notChsTmp = "";}} catch (BadHanyuPinyinOutputFormatCombination e) { e.printStackTrace(); } }return output; } /** * 汉字转换位汉语拼音首字母,英文字符不变 * * @param chines * 汉字 * @return 拼音 */ public static String getShoupin(String chines) { String pinyinName = ""; char[] nameChar = chines.toCharArray(); HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE); 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; } public static void main(String[] args) {System.out.println(getPingyin("张三001"));System.out.println(getShoupin("张三001"));}
}
结果: