利用PinYin4j 实现List中的对象按数字,字母, 汉字排序

要排序的对象:

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;



public class A implements Comparable{
	private String name;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Override
	public int compareTo(A o) {
		String regex = "^\\w.*";
		if (this.getName().matches(regex) || o.getName().matches(regex)) {
			return this.getName().compareTo(o.getName());
		} else {
			return genPinYin(this.getName()).compareTo(genPinYin(o.getName()));
		}
	}
	public static String genPinYin(String input) {
        if (input == null || input.trim().equals("")) {
            return "";
        }
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        //多音字预先转换 这里可以处理一下多音字
        char[] chars =  input.trim().toCharArray();
        StringBuilder output = new StringBuilder();
        try {
            for (char c : chars) {
                if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    output.append(temp[0]);
                } else {
                    output.append(Character.toString(c));
                }
            }
        } catch (Exception e) {
            System.err.println("拼音转换出现未知异常:" + input);
        }
        return output.toString();
    }
  
}

  

排序实现:

 

  

jar 包下载地址: http://pan.baidu.com/s/1sj9A2wl

 

 

你可能感兴趣的:(利用PinYin4j 实现List中的对象按数字,字母, 汉字排序)