Set集合 TreeSet 案例 成绩排序

浏览 24 次     时间 2021-08-24 00:18:51     作者 有勇气的牛排    标签 Java

1 需求

使用TreeSet集合存储多个学生信息(姓名,语文成绩,数学成绩),并遍历该集合

要求:按照总分从高到底出现

思路:

1、定义学生类

2、创建TreeSet集合对象,通过比较器排序进行排序

3、创建学生对象

4、把学生对象添加到集合

5、遍历集合

实战演练

Student.java

package TreeSet2;

public class Student {
    private String name;
    private int chinese;
    private int math;

    public Student() {
    }

    public Student(String name, int chinese, int math) {
        this.name = name;
        this.chinese = chinese;
        this.math = math;
    }

    public String getName() {
        return name;
    }

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

    public int getChinese() {
        return chinese;
    }

    public void setChinese(int chinese) {
        this.chinese = chinese;
    }

    public int getMath() {
        return math;
    }

    public void setMath(int math) {
        this.math = math;
    }

    public int getSum() {
        return this.chinese + this.getMath();
    }

}

TreeSetDemo.java

package TreeSet2;

import sun.reflect.generics.tree.Tree;

import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetDemo {
    public static void main(String[] args) {

        // 创建Tree集合对象,通过比较器排序进行排序
        TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {

//                int num = s2.getMath()+s2.getChinese()-s1.getMath()-s1.getChinese();
                // 总成绩
                int num = s2.getSum() - s1.getSum();

                // 语文成绩升序
                int num2 = num == 0 ? s1.getChinese() - s2.getChinese() : num;

                // 姓名不一样
                int num3 = num2 == 0 ? s1.getName().compareTo(s2.getName()) : num2;

                return num3;
            }
        });

        // 创建学生对象
        Student s1 = new Student("灰太狼", 100, 92);
        Student s2 = new Student("喜洋洋", 92, 99);
        Student s3 = new Student("有勇气的牛排", 99, 100);
        Student s4 = new Student("导演", 96, 97);
        Student s5 = new Student("懒洋洋", 96, 96);

        // 把学生添加到集合
        ts.add(s1);
        ts.add(s2);
        ts.add(s3);
        ts.add(s4);
        ts.add(s5);

        // 遍历集合
        for (Student s : ts) {
            System.out.println(s.getName() + "," + s.getChinese() + "," + s.getMath() + "," + s.getSum());
        }
    }
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。