随笔-汉字转拼音

在开发公司项目中,碰到了需要按照汉字拼音首字母分组的情况,特此记录一下。

maven项目首先导入汉字转拼音的依赖

<!-- 汉字转拼音 -->
        <dependency>
            <groupId>com.belerweb</groupId>
            <artifactId>pinyin4j</artifactId>
            <version>2.5.1</version>
        </dependency>

实现汉字转拼音的方法

/**
     * 将汉字转为拼音
     *
     * @param chinese
     * @return string
     * @throws BadHanyuPinyinOutputFormatCombination
     */
    private String getPinyin(String chinese) throws BadHanyuPinyinOutputFormatCombination {
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();

        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        //设置获得拼音格式
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

        for (char c : arr) {
            if (c > 128) {
                //拼接返回结果的第一种结果
                pybf.append(PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat)[0]);
            } else {
                pybf.append(c);
            }
        }

        return pybf.toString();
    }

按照拼音首字母进行分组

    /**
     * 按照首字母进行分组
     *
     * @param list
     * @return map
     * @throws BadHanyuPinyinOutputFormatCombination
     */
    private List<List<HallDTO>> getPinyinGroup(List<HallDTO> list) throws BadHanyuPinyinOutputFormatCombination {
        List<List<HallDTO>> hallList = new LinkedList<>();

        //输出26个字母
        for (int i = 1; i <= NUMBER_OF_ENGLISH_LETTERS; i++) {
            String word = String.valueOf((char) (96 + i)).toUpperCase();

            List<HallDTO> letter = new LinkedList<>();
            //循环找出首字母一样的数据
            for (HallDTO str : list) {
                String code = null;
                code = getPinyin(str.getUsNameSimple()).substring(0, 1);

                if (word.equals(code)) {
                    letter.add(str);
                }
            }

            hallList.add(letter);
        }

        return hallList;
    }

 

posted @ 2021-01-24 15:02  ADF_CcXx  阅读(65)  评论(0)    收藏  举报