中文首字母排序

使用Java提供的 Collator 類比較.(不推薦)

  1. 原理: 用getInstance(Locale ) 方法進行實例化對象。而後重寫裏面的 compare() 的方法進行比較。
    優勢:排序方法實現簡單.
    缺點:排序結果不是很準確.
  2. 例子:
String[] titles = {"關羽","張飛","公孫瓚","諸葛亮","曹操","劉備","趙雲","微微", "哈哈", "哈", "怡情", "用友", "醫院", "小米", "11", "2", "23", "234", "xiao", "at", "ok", "false"};
        Comparator comparator = Collator.getInstance(java.util.Locale.CHINA);
        Arrays.sort(titles,comparator);
        for(String str:titles){
            System.out.print(str +" ");
        }
  1. 測試結果
    在這裏插入圖片描述

使用pinyin4j比較.(推薦)

  1. 原理:重寫Comparator接口,將中文轉爲拼音,而後進行比較.排序結果準確.php

  2. 引入pinyin4j的jar包java

<!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j -->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
  1. 重寫Comparator接口
public class PinyinComparator implements Comparator<Object> {
    public int compare(Object o1, Object o2) {
        char c1 = ((String) o1).charAt(0);
        char c2 = ((String) o2).charAt(0);
        return concatPinyinStringArray(
                PinyinHelper.toHanyuPinyinStringArray(c1)).compareTo(
                concatPinyinStringArray(PinyinHelper
                        .toHanyuPinyinStringArray(c2)));
    }

    private String concatPinyinStringArray(String[] pinyinArray) {
        StringBuffer pinyinSbf = new StringBuffer();
        if ((pinyinArray != null) && (pinyinArray.length > 0)) {
            for (int i = 0; i < pinyinArray.length; i++) {
                pinyinSbf.append(pinyinArray[i]);
            }
        }
        return pinyinSbf.toString();
    }

    public static void main(String[] args) {
        String[] arr = {"關羽2", "關羽1", "張飛", "公孫瓚", "諸葛亮", "曹操", "劉備", "趙雲", "微微", "哈哈", "哈", "怡情", "用友", "醫院", "小米", "張三", "李四", "王五", "趙六", "JAVA", "java", "AVA", "php", "PHP", "123", "2", "234", "126", "011", "123", "$%$#", "哈哈A",
                "1哈哈A", "1哈哈b", "1哈哈a", "哈哈", "哈", "怡情"};
        List<String> list = Arrays.asList(arr);
        Collections.sort(list, new PinyinComparator());
        System.out.println(list);
    }
}
  1. 測試結果
    在這裏插入圖片描述
相關文章
相關標籤/搜索