1. 程式人生 > >根據拼音排序

根據拼音排序

需求:將一組資料按某一欄位中文拼音排序

PinyinComparator comparator = new PinyinComparator();  
        Collections.sort(strList, comparator); 

其中strList中放置了資料,可以是任何物件,但要對PinyinComparator中的compare進行對應的修改,我Demo中為String[]

2、PinyinComparator排序類


public class PinyinComparator implements Comparator<Object> {
    /**
     * 比較兩個字串
     */
public int compare(Object o1, Object o2) { String[] name1 = (String[]) o1; String[] name2 = (String[]) o2; String str1 = getPingYin(name1[0]); String str2 = getPingYin(name2[0]); int flag = str1.compareTo(str2); return flag; } /** * 將字串中的中文轉化為拼音,其他字元不變 * * @param
inputString * @return */
public String getPingYin(String inputString) { HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat(); format.setCaseType(HanyuPinyinCaseType.LOWERCASE); format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); format.setVCharType(HanyuPinyinVCharType.WITH_V); char[] input = inputString.trim().toCharArray();// 把字串轉化成字元陣列
String output = ""; try { for (int i = 0; i < input.length; i++) { // \\u4E00是unicode編碼,判斷是不是中文 if (java.lang.Character.toString(input[i]).matches( "[\\u4E00-\\u9FA5]+")) { // 將漢語拼音的全拼存到temp陣列 String[] temp = PinyinHelper.toHanyuPinyinStringArray( input[i], format); // 取拼音的第一個讀音 output += temp[0]; } // 大寫字母轉化成小寫字母 else if (input[i] > 'A' && input[i] < 'Z') { output += java.lang.Character.toString(input[i]); output = output.toLowerCase(); } output += java.lang.Character.toString(input[i]); } } catch (Exception e) { Log.e("Exception", e.toString()); } return output; } }

後來根據我們專案的實際情況

    public static class PinyinComparator implements Comparator<Map<?, ?>>{
        private String mSortingKey;

        public PinyinComparator(String sortingKey) {
            mSortingKey = sortingKey;
        }

        public void setSortingKey(String sortingKey) {
            mSortingKey = sortingKey;
        }
        public int compare(Map<?, ?> map1, Map<?, ?> map2){
            Object o1 = map1.get(mSortingKey);
            Object o2 = map2.get(mSortingKey);
            String name1 = (String) o1;
            String name2 = (String) o2;
            String str1 = getPinYin(name1);
            String str2 = getPinYin(name2);
            int flag = str1.compareTo(str2);
            return flag;
        }
    }

在Android.mk檔案中這樣改

  ...
LOCAL_STATIC_JAVA_LIBRARIES := pinyin4j666 \
                               android-support-v4 android-support-v13 jsr305 \
                               com.mediatek.lbs.em2.utils \
                               com.mediatek.settings.ext
 ...

include $(CLEAR_VARS)
LOCAL_PREBUILT_STATIC_JAVA_LIBRARIES := pinyin4j666:libs/pinyin4j-2.5.0.jar
include $(BUILD_MULTI_PREBUILT)