List中存放若干学生对象(学生有学号,姓名,性别等属性),去除List中重复的元素,并按学号降序输出。(请百度并利用LinkedHashSet集合,既不会重复,同时有可预测的顺序即输入顺序)

public class Student {
    private int ID;
    private String name;
    private char sex;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return ID == student.ID &&
                sex == student.sex &&
                Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(ID, name, sex);
    }

    @Override
    public String toString() {
        return "Student{" +
                "ID=" + ID +
                ", name='" + name + '\'' +
                ", sex=" + sex +
                '}';
    }

    public Student(int ID, String name, char sex) {
        this.ID = ID;
        this.name = name;
        this.sex = sex;
    }

    public int getID() {
        return ID;
    }

    public void setID(int ID) {
        this.ID = ID;
    }

    public String getName() {
        return name;
    }

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

    public char getSex() {
        return sex;
    }

    public void setSex(char sex) {
        this.sex = sex;
    }
}

public class TestStudent {
    public static void main(String[] args) {
        List<Object> s = new ArrayList<>();
        s.add(new Student(1003, "小张", '男'));
        s.add(new Student(1005, "小王", '女'));
        s.add(new Student(1008, "小李", '男'));
        s.add(new Student(1005, "小王", '女'));
        s.add(new Student(1002, "小赵", '女'));
        s.add(new Student(1008, "小李", '男'));
        s.add(new Student(1006, "小孙", '男'));
        class Rule implements Comparator {

            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Student && o2 instanceof Student) {
                    Student s1 = (Student) o1;
                    Student s2 = (Student) o2;
                    if (s1.getID() > s2.getID()) return -1;
                    if (s1.getID() < s2.getID()) return 1;
                    return 0;
                }
                throw new RuntimeException("必须是Student类型");
            }
        }
        Collections.sort(s, new Rule());
        Order(s);
        Iterator iterator = s.iterator();
        System.out.println("去除重复并将学生按降序排列后:");
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }

    public static void Order(List<Object> s) {
        LinkedHashSet<Object> l = new LinkedHashSet<>();
        l.addAll(s);//将list集合中所有的元素添加到新集合l中
        s.clear();//清除原来集合
        s.addAll(l);//将去除了重复元素的集合添加到s集合中
    }
}

输出结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44084434/article/details/91390427