Java对象中的字段按汉语拼音首字母排序

话不多说看代码
package com.*;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
//测试类
public class Demo {

    @Test
    public void test_sort_pinyin() {
        List userList = new ArrayList<>();
        userList.add(new User("博爱大",22));
        userList.add(new User("华三",22));
        userList.add(new User("是你吗",22));
        userList.add(new User("不对",22));
        userList.add(new User("疫情",22));
        userList.add(new User("1哈哈",22));
        userList.add(new User("张三",22));
        userList.add(new User("李四",22));
        userList.add(new User("王五",22));
        userList.add(new User("赵六",22));
        userList.add(new User("JAVA",22));
        userList.add(new User("$%$",22));
        userList.add(new User("123",22));
        userList.add(new User("1哈哈A",22));
        userList.add(new User("1哈哈b",22));

        Collections.sort(userList, new PinyinComparator());
        System.out.println(userList.toString());
    }
}
package com.*;
import java.io.Serializable;
//用户对象类
public class User implements Serializable {

    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
package com.itcast;
import net.sourceforge.pinyin4j.PinyinHelper;
import java.util.Comparator;
//比较器类,需要使用pinyin4j 包
public class PinyinComparator implements Comparator {
    public int compare(User o1, User o2) {
        char c1 = (o1.getName()).charAt(0);
        char c2 = (o2.getName()).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();
    }
}

你可能感兴趣的:(Java,排序,汉字)