中文首字母排序

使用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. 测试结果
    在这里插入图片描述
相关文章
相关标签/搜索