List集合中的对象按中文首字母排序

话不多说,上代码


package com.kevin.practice.tmp;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.text.Collator;
import java.util.*;

/**
 * @Description 测试
 * @Author
 * @Date 2020/3/3 9:25
 */
@RunWith(JUnit4.class)
public class Test01 {


    private List<Employee> initList() {
        return Arrays.asList(
                new Employee("111", 8, 7777.77),
                new Employee("Kevin", 8, 7777.77),
                new Employee("张三", 18, 9999.99),
                new Employee("李四", 37, 5555.99),
                new Employee("王五", 50, 6666.66),
                new Employee("赵六", 16, 3333.33),
                new Employee("田七", 8, 7777.77),
                new Employee("AAAA", 8, 7777.77)
        );
    }

    @Test
    public void test01() {
        List<Employee> list = initList();
        Comparator comparator = Collator.getInstance(Locale.CHINA);
        Collections.sort(list, new Comparator<Employee>() {
            @Override
            public int compare(Employee o1, Employee o2) {
                return comparator.compare(o1.getName(), o2.getName());
            }
        });
        list.stream().forEach(System.out::println);
    }

    @Data
    @AllArgsConstructor
    @ToString
    public static class Employee {
        private String name;
        private int age;
        private double income;
    }
}

看一下运行结果:


这里添加数字与字母,如果存在数字,字母,中文情况下,排序规则如下:
数字 -> 字母 -> 中文

posted @ 2020-03-03 11:04  灬毛毛  阅读(4109)  评论(0编辑  收藏  举报