汉字排序、提取汉字首字母

一、通过Stream流进行汉字排序:

  1. Comparator<Object> comparator = Collator.getInstance(java.util.Locale.CHINA);
  2. CompanyPhonesDto companyPhonesDto = new CompanyPhonesDto();
  3. List<String> companyName = new ArrayList<>();
  4. // 数据列表(查询语句)
  5. List<InsuranceCompany> companies = insuranceCompanyService.list();
  6. // 汉字排序
  7. companies = companies.stream().sorted((p1, p2) -> comparator.compare(p1.getCompanyName(), p2.getCompanyName())).collect(Collectors.toList());

二、提取汉字首字母

2.1 :引入maven

  1. <!-- pinyin4j -->
  2. <dependency>
  3. <groupId>com.belerweb</groupId>
  4. <artifactId>pinyin4j</artifactId>
  5. <version>2.5.1</version>
  6. </dependency>

2.2 :代码实现

  1. String str = "中文";
  2. StringBuilder convert = new StringBuilder();
  3. // 如果要获取字符串中每个汉字的首字母,放开for循环
  4. //for (int j = 0; j < str.length(); j++) {
  5. char word = str.charAt(0);
  6. String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
  7. if (pinyinArray != null) {
  8. convert.append(pinyinArray[0].charAt(0));
  9. } else {
  10. convert.append(word);
  11. }
  12. // }
  13. System.out.println(convert.toString().toUpperCase());