【java】----输出不重复且降序

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

import java.util.Objects;

public class Student implements Comparable<Student> {

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

    private int code;
    private String name;
    private char sex;

    public String getName() {
        return name;
    }

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

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }


    public char getSex() {
        return sex;
    }

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

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


    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || getClass() != obj.getClass()) return false;
        Student student = (Student) obj;
        return code == student.code &&
                sex == student.sex &&
                name.equals(student.name);

        }

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

    @Override
    public int compareTo(Student o) {

        if(this.code > o.code) return -1;
        if(this.sex > o.sex) return  -1;
        return 0;
    }

}
import java.util.*;

public class Test_student {
    public static void main(String[] args) {
//.List中存放若干学生对象(学生有学号,姓名,性别属性)
        List<Student> list = new ArrayList<>();
        list.add(new Student(344,"卡卡",'女'));
        list.add(new Student(345,"佳佳",'女'));
        list.add(new Student(346,"小于",'男'));
        list.add(new Student(344,"卡卡",'女'));
        list.add(new Student(347,"张三",'男'));
        list.add(new Student(343,"李四",'女'));

//去除List中重复的元素,并按学号降序输出
        List<Student> studentList = new ArrayList<>(new LinkedHashSet<Student>(list));
        System.out.println("原集合:" + list);
        System.out.println("去重后的集合:" + studentList);
        Collections.sort(studentList, Collections.reverseOrder());
        TreeSet tree = new TreeSet();
        tree.addAll(studentList);
        System.out.println("去重降序后的集合:" + tree);


    }
}

![在这里插入图片描述](https://img-blog.csdnimg.cn/20190610210255971.PNG)

你可能感兴趣的:(Java,Java算法)