List實現按某屬性首字母排序

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

/**
 * @author Peacock__
 * @version 1.0
 * @date 2020/3/10 14:03
 */
public class TempTest {

    public static void main(String[] args) {
        List<User> list = new ArrayList<>();
        list.add(new User(1L,"徐五",20));
        list.add(new User(2L,"李四",20));
        list.add(new User(3L,"張三",20));
        list.add(new User(4L,"郭七",20));
        list.add(new User(5L,"董八",20));
        list.add(new User(6L,"曹二",20));
        list.add(new User(7L,"安一",20));
        list.add(new User(8L,"武大",20));

        // 獲取中文環境
        Comparator comparator = Collator.getInstance(Locale.CHINA);
        // 排序實現
        Collections.sort(list, (u1, u2) -> {
            return comparator.compare(u1.getName(), u2.getName());
        });

        list.stream().forEach(i -> {
            System.out.println(i.getName());
        });
    }

}

class User{
    private Long id;
    private String name;
    private Integer age;

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

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    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;
    }
}

輸出結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章