侧边栏壁纸
博主头像
suringYu

走走停停

  • 累计撰写 50 篇文章
  • 累计创建 18 个标签
  • 累计收到 3 条评论

目 录CONTENT

文章目录

TreeSet集合的排序

suringYu
2021-12-25 / 0 评论 / 0 点赞 / 289 阅读 / 2,855 字

假设排序目的:将学生信息进行年龄排序,如果年龄相同按姓名排序

注:student类中getNamePinYin方法中使用了TinyPinyin汉字转拼音库,用于中文转拼音便于姓名排序

student类

public class student{
    private Integer age;
    private String name;

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    public String toString() {
        return "student{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public String getNamePinYin(){
        char[] chars = this.getName().toCharArray();
        StringBuilder stringBuilder = new StringBuilder();
        for (char c : chars) {
            stringBuilder.append(Pinyin.toPinyin(c));
        }
        return stringBuilder.toString();
    }
}

1、自然排序Comparable

通过实现Comparable接口中的compareTo方法进行排序,在compareTo方法中写入排序规则

student类

public class student implements Comparable<student>{  
    
    ...
    // 省略掉了上面的重复代码
	@Override
    public int compareTo(student o) {
        int n = this.getAge() - o.getAge();
        return n == 0 ? this.getNamePinYin().compareTo(o.getNamePinYin()) : n;
    }
}

将需要排序的student对象添加到TreeSet集合中,并输出

public static void main(String[] args) throws Exception{
    TreeSet<student> st = new TreeSet<student>();
    st.add(new student(23,"张三"));
    st.add(new student(21,"王五"));
    st.add(new student(21,"李四"));
    st.add(new student(30,"老刘"));
    st.add(new student(22,"阿坤"));
    st.add(new student(22,"小鸿"));
    st.add(new student(1,"未知"));
    for (student s: st) {
        System.out.println(s);
    }
}

控制台输出结果

输出结果

2、比较器Comparator

在定义TreeSet集合的时候就传入一个比较器Comparator,里面定义我们自己的排序规则

public static void main(String[] args) throws Exception{
    TreeSet<student> st = new TreeSet<student>(new Comparator<student>() {
        @Override
        public int compare(student o1, student o2) {
            int n = o1.getAge() - o2.getAge();
            return n == 0 ? o1.getNamePinYin().compareTo(o2.getNamePinYin()) : n;
        }
    });
    st.add(new student(23,"张三"));
    st.add(new student(21,"王五"));
    st.add(new student(21,"李四"));
    st.add(new student(30,"老刘"));
    st.add(new student(22,"阿坤"));
    st.add(new student(22,"小鸿"));
    st.add(new student(1,"未知"));
    for (student s: st) {
        System.out.println(s);
    }
}

控制台输出结果

TahbQI.png

附录:TinyPinyin汉字转拼音库

GitHub地址:https://github.com/promeG/TinyPinyin
maven引入:

<dependency>
    <groupId>com.github.promeg</groupId>
    <artifactId>tinypinyin</artifactId>
    <version>2.0.3</version>
</dependency>
0

评论区