pinyin4j 汉字排序

pinyin-4j官网

Bean对象:

public class NameBean {
	private String name;

	public String getName() {
		return name;
	}

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

	public String getNameFirstChar() {
		return getFirstChar(name);
	}

	// 获得字符串的首字母 首字符 转汉语拼音
	public String getFirstChar(String value) {
		// 首字符
		char firstChar = value.charAt(0);
		// 首字母分类
		String first = null;
		// 是否是非汉字
		String[] print = PinyinHelper.toHanyuPinyinStringArray(firstChar);

		if (print == null) {

			// 将小写字母改成大写
			if ((firstChar >= 97 && firstChar <= 122)) {
				firstChar -= 32;
			}
			if (firstChar >= 65 && firstChar <= 90) {
				first = String.valueOf((char) firstChar);
			} else {
				// 认为首字符为数字或者特殊字符
				first = "#";
			}
		} else {
			// 如果是中文 分类大写字母
			first = String.valueOf((char) (print[0].charAt(0) - 32));
		}
		if (first == null) {
			first = "?";
		}
		return first;
	}
}
实现比较的接口:
public class MyComparator implements Comparator<NameBean> {
	String ostr1;
	String ostr2;

	@Override
	public int compare(NameBean bean1, NameBean bean2) {
		ostr1 = bean1.getNameFirstChar();
		ostr2 = bean2.getNameFirstChar();
		
		for (int i = 0; i < ostr1.length() && i < ostr2.length(); i++) {

			int codePoint1 = ostr1.charAt(i);
			int codePoint2 = ostr2.charAt(i);
			if (Character.isSupplementaryCodePoint(codePoint1)
					|| Character.isSupplementaryCodePoint(codePoint2)) {
				i++;
			}
			if (codePoint1 != codePoint2) {
				// 拼音字符
				if (Character.isSupplementaryCodePoint(codePoint1)
						|| Character.isSupplementaryCodePoint(codePoint2)) {
					return codePoint1 - codePoint2;
				}
				String pinyin1 = pinyin((char) codePoint1);
				String pinyin2 = pinyin((char) codePoint2);

				if (pinyin1 != null && pinyin2 != null) { // 两个字符都是汉字
					if (!pinyin1.equals(pinyin2)) {
						return pinyin1.compareTo(pinyin2);
					}
				} else {
					return codePoint1 - codePoint2;
				}
			}
		}
		return ostr1.length() - ostr2.length();
	}

	// 获得汉字拼音的首字符
	private String pinyin(char c) {
		String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(c);
		if (pinyins == null) {
			return null;
		}
		return pinyins[0];
	}
}
测试:
public class TestMain {
	public static void main(String[] args) {
		String[] str = { "计算机", "网络", "回收站", "Fire", "驱动精灵", "百度", "白色", "无恐",
				"lxz", "A酱", "芙兰", "鱼鱼", "妹妹", "你好", "林小姐", "联盟", "L",
				"xdsfsdggsdsf", "星星", "靴刀誓死", "Java", "倒塌", "黑人", "a妹", "aYa",
				"Admin", "ali", "阿san", };
		List<NameBean> arrList = new ArrayList<NameBean>();
		for (String s : str) {
			NameBean bean = new NameBean();
			bean.setName(s);
			arrList.add(bean);
		}

		MyComparator compare = new MyComparator();
		Collections.sort(arrList, compare);

		for (NameBean b : arrList) {
			System.out.println(b.getNameFirstChar() + ";" + b.getName());
		}
	}
}




你可能感兴趣的:(pinyin4j)