利用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<A>{

	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();

    }

  

}

  

排序实现:

 

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;



public class Test {



	public static void main(String[] args) {

		A a1 = new A();  A a2 = new A();

		A a3 = new A();  A a4 = new A();

		A a5 = new A();  A a6 = new A();

		A a7 = new A();  A a8 = new A();



		a1.setName("二维码"); a2.setName("回调");

		a3.setName("接口"); a4.setName("服务窗");

		a5.setName("123"); a6.setName("456");

		a7.setName("zbc"); a8.setName("Abhj");

		

		List<A> list = new ArrayList<A>();

		list.add(a1); list.add(a2); list.add(a3); list.add(a4);

		list.add(a5); list.add(a6); list.add(a7); list.add(a8);

		

		Collections.sort(list);

		

		for (A a : list) {

			System.out.println(a.getName());

		}

	}

}

  

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

 

 

你可能感兴趣的:(pinyin4j)