Java sorts and groups according to the first letter of Chinese characters +pinyin4j

Use pinyin4j

<dependency>
			<groupId>com.belerweb</groupId>
			<artifactId>pinyin4j</artifactId>
			<version>2.5.0</version>
		</dependency>

real case code

    private List<LetterSortBo> buildBrandLetterSort(List<BrandDto> brandList) {
        List<LetterSortBo> sortList = Lists.newArrayList();
        if (CollectionUtils.isEmpty(brandList)) {
            return sortList;
        }
        //输出26个字母
        Map<String, List<CommonBo>> map = new TreeMap<>();
        for (int i = 1; i <= 26; i++) {
            String letter = String.valueOf((char) (96 + i)).toUpperCase();
            List<CommonBo> letterData = new ArrayList<>();
            //删除不能用ForEach方法偶尔会抛出异常【ConcurrentModificationException】,终止循环
            Iterator<BrandDto> iterator = brandList.iterator();
            while (iterator.hasNext()) {
                BrandDto brandDto = iterator.next();
                String str = getFullSpell(brandDto.getName());
                if (letter.equals(str)) {
                    letterData.add(new CommonBo(brandDto.getId(), brandDto.getName(), brandDto.getLogoUrl()));
                    iterator.remove();
                }
            }
            map.put(letter, letterData);
        }
        Set<String> keySet = map.keySet();
        for (String key : keySet) {
            sortList.add(new LetterSortBo(key, map.get(key)));
        }
        //特殊字符
        if (CollectionUtils.isNotEmpty(brandList)) {
            sortList.add(new LetterSortBo("#", brandList.stream().map(p -> {
                return new CommonBo(p.getId(), p.getName(), p.getLogoUrl());
            }).collect(Collectors.toList())));
        }
        return sortList;
    }

    private String getFullSpell(String chinese) {
        chinese = chinese.trim();
        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]);
            }
        }
        String str = pybf.toString();
        if (str.length() > 0) {
            return str.substring(0, 1).toUpperCase();
        } else {
            return str;
        }
    }

Guess you like

Origin blog.csdn.net/weixin_43832604/article/details/121492233