背景
有个项目需要将一批字符串的拼音首字母输出并大写,写了个工具类。
实现
需要引入外部jar。
<dependency><groupId>com.belerweb</groupId><artifactId>pinyin4j</artifactId><version>2.5.1</version>
</dependency>
public static void main(String[] args) {List<String> list = Arrays.asList("中国", "北京");System.out.println(getBelongLetterMap(list));
}/*** 根据入参的list返回分组map*/
public static Map<String, String> getBelongLetterMap(List<String> list) {if (CollectionUtils.isEmpty(list)) {return Maps.newHashMap();}Comparator com = Collator.getInstance(Locale.CHINA);Collections.sort(list, com);Map<String, String> map = new TreeMap<String, String>();for (int i = 1; i <= 26; i++) {String word = String.valueOf((char) (96 + i)).toUpperCase();for (String str : list) {String fullSpell = getFullSpell(str);if (StringUtils.isEmpty(fullSpell)) {continue;}String zm = fullSpell.substring(0, 1);if (word.equalsIgnoreCase(zm)) {map.put(str, word);}}}return map;
}/*** 获取汉字串拼音,英文字符不变*/
public static String getFullSpell(String chinese) {if (StringUtils.isEmpty(chinese)) {return null;}StringBuilder pybf = new StringBuilder();char[] arr = chinese.toCharArray();HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);for (int i = 0; i < arr.length; i++) {if (arr[i] > 128) {try {pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);} catch (Exception e) {if (i == 0) {//第一个字符就异常 那必定是特殊字符 直接返回nullreturn null;}}} else {pybf.append(arr[i]);}}return pybf.toString();
}
输出: