Life has its own fate, and meeting may not be accidental.

0%

SpringBoot-中文按首字母分组分类

项目需要用到名字选择,但是太多了需要按照首字母排序。_

导入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 {
/**
     * 获取汉字串拼音,英文字符不变
     * @param chinese 汉字串
     * @return 汉语拼音
     */
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);
}
}