读书人

List聚合行中英混合排序

发布时间: 2012-12-21 12:03:49 作者: rapoo

List集合行中英混合排序
示例:
假设有这样的十条记录:
import java.util.Comparator;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;import net.sourceforge.pinyin4j.format.exception.*;@SuppressWarnings("unchecked")public class AuthorVOCompare implements Comparator {public int compare(Object op1, Object op2) {RecordInfo record1 = (RecordInfo) op1;String o1 = record1.getRecordtemp();RecordInfo record2= (RecordInfo) op2;String o2 = record2. getRecordtemp ();for (int i = 0; i < o1.length() && i < o2.length(); i++) {int codePoint1 = o1.charAt(i);int codePoint2 = o2.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)) {//一尤重要,如果用的是compareTo是不忽略大小的return pinyin1. compareToIgnoreCase (pinyin2);}} else {return codePoint1 - codePoint2;}}}return o1.length() - o2.length();}/**对中英文排序**/private String pinyin(char c) {if (String.valueOf(c) == null || String.valueOf(c).length() == 0) {return "";}HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();format.setCaseType(HanyuPinyinCaseType.LOWERCASE);format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);format.setVCharType(HanyuPinyinVCharType.WITH_V);String output = "";try {if (java.lang.Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) {String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, format);if (temp != null && temp.length > 0) {output += temp[0];}} else {output += java.lang.Character.toString(c);}} catch (BadHanyuPinyinOutputFormatCombination e) {e.printStackTrace();}return output;}}
这个类中需要引入一个jar包:pinyin4j-2.5.0.jar,主要用于拼音的排序,可以网上下载。


ps:本文版,代部分摘自。

读书人网 >编程

热点推荐