我爱编程

Java中文按照拼音排序(含中文)

2018-04-15  本文已影响47人  一路摇到顶

添加maven,中文转拼音 工具jar

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

中文转拼音

public class PinyinUtil {

    private static Logger logger = LoggerFactory.getLogger(PinyinUtil.class);
    private static HanyuPinyinOutputFormat hanYuPinOutputFormat = new HanyuPinyinOutputFormat();
    private static Map<String,String> staticChars = new HashMap<String,String>();

    static{
        //输出设置,大小写,音标方式等
        hanYuPinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);   
        hanYuPinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        hanYuPinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);  

        staticChars.put("长", "chang");
    }


    public static String getChinesPinyin(String code){

        if(code == null) return null;

        char[] codeChar = code.toCharArray();

        StringBuilder sb = new StringBuilder();

        for(char c : codeChar){

            // 是中文或者a-z或者A-Z转换拼音
            if (String.valueOf(c).matches("[\\u4E00-\\u9FA5]+")) {
                try {

                    String key = String.valueOf(c);

                    if(staticChars.containsKey(key)){
                        sb.append(staticChars.get(key));
                        continue;
                    }

                    String[]  pins = PinyinHelper.toHanyuPinyinStringArray(c, hanYuPinOutputFormat);

                    if(pins != null && pins.length > 0){
                        sb.append(pins[0]);
                    }

                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    logger.error(e.getMessage(),e);
                }
            } else if (((int) c >= 65 && (int) c <= 90)
                    || ((int) c >= 97 && (int) c <= 122)) {
                sb.append(String.valueOf(c));
            }else{
                sb.append(String.valueOf(c));
            }

        }

        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(getChinesPinyin("长安"));
    }
}

排序封装类

public class StringOrderWrapper implements Comparable<StringOrderWrapper> {
    String name = null;
    Object data = null;

    public StringOrderWrapper(String name,Object date) {
        this.name = name;
        this.data = date;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return String.valueOf(name);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }

        if (obj instanceof StringOrderWrapper) {
            StringOrderWrapper other = (StringOrderWrapper) obj;
            if (null == this.name) {
                return false;
            } else {
                return this.name.equals(other.name);
            }
        }
        return false;
    }

    /**
     *
     * @param wrapper
     * @return
     */
    // 比较方法,相当于减法。 (return this - wrapper)
    public int compareTo(StringOrderWrapper wrapper) {
        if (null == wrapper) {
            return 1;
        }
        // 直接相等
        if (this == wrapper || this.equals(wrapper)) {
            return 0;
        }
        String name1 = this.name;
        String name2 = wrapper.name;
        if(name1.compareTo(name2)==0)
        {
            return 0;
        }
        // 特殊情形,name有一个为空的情况.
        if (StringUtils.isEmpty(name1)) {
            // 都为空,认为相对
            if (StringUtils.isEmpty(name2)) {
                return 0;
            } else {
                return -1;
            }
        } else if (StringUtils.isEmpty(name2)) {
            return 1;
        }
        // 中间 1-多个数字
        Pattern pattern = Pattern.compile("\\D*(\\d+)\\D*");
        Matcher matcher1 = pattern.matcher(name1);
        Matcher matcher2 = pattern.matcher(name2);
        //
        int index1_step = 0;
        int index2_step = 0;
        while (matcher1.find()) {
            String s1 = matcher1.group(1);
            String s2 = null;
            if (matcher2.find()) {
                s2 = matcher2.group(1);
            }else{
                break;
            }
            int index1 = name1.indexOf(s1, index1_step);
            int index2 = name2.indexOf(s2, index2_step);
            //
            index1_step = index1;
            index2_step = index2;
            // 索引相等的情况下
            if (index1 == index2) {
                String pre1 = name1.substring(0, index1);
                String pre2 = name2.substring(0, index2);
                if (pre1.equals(pre2)) {
                    //
                    long num1 = Long.parseLong(s1);
                    long num2 = Long.parseLong(s2);
                    //
                    if (num1 == num2) {
                        // 比较下一组
                        continue;
                    } else {
                        return (int) (num1 - num2);
                    }
                } else {
                    break;
                }
            } else {
                break;
            }
        }

        // 最后的情形.
        return PinyinUtil.getChinesPinyin(this.name).compareTo(PinyinUtil.getChinesPinyin(wrapper.name));
    }

    private int comparePinyin(String name1,String name2){
        return PinyinUtil.getChinesPinyin(name1).compareTo(PinyinUtil.getChinesPinyin(name2));
    }
}

使用

//date 是需要排序的数据集合
List<StringOrderWrapper> orderWrapperList = new ArrayList<>(data.size());
       for (Item item : data) {
         //设置 中文名字
           orderWrapperList.add(new StringOrderWrapper(item.getName(), item));
       }
       //进行排序
       Collections.sort(orderWrapperList);
上一篇下一篇

猜你喜欢

热点阅读