TreeSet集合的一个比较器排序去重案例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/euller/article/details/70185754

Student基础信息

package TreeSetDemo;

public class Student implements Comparable<Student>{
    //学生姓名
    private String name;
    //学生年龄
    private int age;

    //无参构造
    public Student() {
        // TODO Auto-generated constructor stub
    }

    // 带参构造
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    //getXxx() setXxx()方法
    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    @Override
    public int compareTo(Student s) {
        //按照年龄排序,主要条件
        int num = this.age- s.age;

        //如果年龄相同,比较姓名,如果姓名相同的话,才是同一个对象
        int num1 = num == 0 ? this.name.compareTo(s.name) : num;
        return num1;
    }
}

TreeSetDemo类

package TreeSetDemo;

import java.util.TreeSet;

public class TreeSetDemo1 {
    public static void main(String[] args) {
        //创建集合对象
        TreeSet<Student> ts = new TreeSet<Student>();

        //创建元素
        Student s1 = new Student("hello", 27);
        Student s2 = new Student("world", 66);
        Student s3 = new Student("hello", 27);
        Student s4 = new Student("java", 63);
        Student s5 = new Student("world", 65);
        Student s6 = new Student("eclipse", 99);

        //添加元素
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);
        ts.add(s6);

        //遍历
        for(Student s : ts){
            System.out.println(s.getName() + "-------" + s.getAge());
        }

    }
}
阅读更多
换一批

没有更多推荐了,返回首页