Android 汉字首字母排序

时间:2022-07-22 08:01:25

需要用到的方法:

用到jar包: pinYin4j.jar

 /** 
     * 汉字转换位汉语拼音首字母,英文字符不变 
     * @param chines 汉字 
     * @return 拼音 
     */  
     public static String converterToFirstSpell(String chines){         
         String pinyinName = "";  
         char[] nameChar = chines.toCharArray();  
         HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();  
         defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);  
         defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);  
         for (int i = 0; i < nameChar.length; i++) {  
             if (nameChar[i] > 128) {  
                 try {  
                     pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0].charAt(0);  
                 } catch (BadHanyuPinyinOutputFormatCombination e) {  
                     e.printStackTrace();  
                 }  
             }else{  
                 pinyinName += nameChar[i];  
             }  
         }  
         return pinyinName;  
     }  

排序方法:

  // 汉字排序

        Collections.sort(contactList, new Comparator<User>() {

            @Override
            public int compare(User lhs, User rhs) {
                String s1=converterToFirstSpell(lhs.getNick());
                String s2=converterToFirstSpell(rhs.getNick());
                return Collator.getInstance(Locale.ENGLISH).compare(s1, s2); 
//                return lhs.getNick().compareTo(rhs.getNick());
                
            }
        });