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