Java中 集合/对象按中文首字母排序

代码实现如下:

1、实体

import lombok.Data;

@Data
public class Car

{
    private Integer id;

    private String name;

    private Integer number;

    private Integer price;

    private String leader;

  
}

 

2、测试

import com.temporary.model.Car;

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

/**
 * @author Han
 * @Description
 * @date 2022/8/25
 */
public class Test037
{
    public static void main(String[] args)
    {
        List<Car> cars = new ArrayList();

        Car car1 = new Car();
        car1.setName("雅阁");
        cars.add(car1);

        car1 = new Car();
        car1.setName("奔驰");
        cars.add(car1);

        car1 = new Car();
        car1.setName("奥迪");
        cars.add(car1);

        car1 = new Car();
        car1.setName("凯美瑞");
        cars.add(car1);

        car1 = new Car();
        car1.setName("君威");
        cars.add(car1);

        // 1 通过java 8 stream流进行处理
        Collection<String> strings = cars.stream().map(Car::getName).sorted(Collator.getInstance(Locale.CHINA)).collect(Collectors.toList());
        
        //2 对集合对象排序 还是按照名称
        sort(cars);
    }
    
    public static void sort(List<Car> carList)
    {
        // 获取中文环境
        Collator comparator = Collator.getInstance(Locale.CHINA);
        carList.sort((e1, e2) -> {
            return comparator.compare(e1.getName(), e2.getName());
        });
        
        carList.forEach(System.out::println);
        System.out.println(carList);
    }
}

 

3、运行结果

 

posted @ 2022-08-25 11:19  云村的王子  阅读(448)  评论(0编辑  收藏  举报