汉字排序、提取汉字首字母
一、通过Stream流进行汉字排序:
Comparator<Object> comparator = Collator.getInstance(java.util.Locale.CHINA);
CompanyPhonesDto companyPhonesDto = new CompanyPhonesDto();
List<String> companyName = new ArrayList<>();
// 数据列表(查询语句)
List<InsuranceCompany> companies = insuranceCompanyService.list();
// 汉字排序
companies = companies.stream().sorted((p1, p2) -> comparator.compare(p1.getCompanyName(), p2.getCompanyName())).collect(Collectors.toList());
二、提取汉字首字母
2.1 :引入maven
<!-- pinyin4j -->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
2.2 :代码实现
String str = "中文";
StringBuilder convert = new StringBuilder();
// 如果要获取字符串中每个汉字的首字母,放开for循环
//for (int j = 0; j < str.length(); j++) {
char word = str.charAt(0);
String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
if (pinyinArray != null) {
convert.append(pinyinArray[0].charAt(0));
} else {
convert.append(word);
}
// }
System.out.println(convert.toString().toUpperCase());