项目需要用到名字选择,但是太多了需要按照首字母排序。_
导入pinyin4j依赖
1 | <dependency> |
2 | <groupId>com.belerweb</groupId> |
3 | <artifactId>pinyin4j</artifactId> |
4 | <version>2.5.0</version> |
5 | </dependency> |
PinYinUtil拼音类实现代码
1 | package com.example.logSystem.pojo; |
2 | import net.sourceforge.pinyin4j.PinyinHelper; |
3 | import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; |
4 | import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; |
5 | import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; |
6 | import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; |
7 |
|
8 |
|
9 |
|
10 | public class PinYinUtil { |
11 | |
12 |
|
13 |
|
14 |
|
15 |
|
16 | public String getFullSpell(String chinese){ |
17 | StringBuffer pybf = new StringBuffer(); |
18 | char[] arr = chinese.toCharArray(); |
19 | HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat(); |
20 | defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE); |
21 | defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); |
22 | for (int i = 0; i < arr.length; i++) { |
23 | if (arr[i] > 128) { |
24 | try { |
25 | pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]); |
26 | } catch (BadHanyuPinyinOutputFormatCombination e) { |
27 | e.printStackTrace(); |
28 | } |
29 | } |
30 | else { |
31 | pybf.append(arr[i]); |
32 | } |
33 | } |
34 | return pybf.toString(); |
35 | } |
36 | } |
利用
1 | List<User> list1= userMapper.selectUser(); |
2 | List<Map<String,Object>> list2=new ArrayList<>(); |
3 | int sum=0; |
4 | for(int i=1;i<=26;i++){ |
5 | Map<String,Object> map=new HashMap<>(); |
6 | String big = String.valueOf((char)(96+i)).toUpperCase(); |
7 | String little = big.toLowerCase(); |
8 | |
9 | List<Map<String,Object>> list3=new ArrayList<>(); |
10 | for(int j=0;j<list1.size();j++){ |
11 | PinYinUtil pinyin = new PinYinUtil(); |
12 | String zm = pinyin.getFullSpell(list1.get(j).getTeachername().substring(0,1)).substring(0,1); |
13 | if(big.equals(zm)||little.equals(zm)){ |
14 | Map<String, Object> map1 = new HashMap<>(); |
15 | map1.put("text", list1.get(j).getTeachername()); |
16 | map1.put("id", sum); |
17 | sum++; |
18 | list3.add(map1); |
19 | } |
20 | } |
21 | if(list3.size()!=0) { |
22 | map.put("text", big); |
23 | map.put("children", list3); |
24 | list2.add(map); |
25 | } |
26 | } |