JAVA基础 练习-14-TreeSet集合成绩排序

JAVA基础 练习-14-TreeSet集合成绩排序

📝 需求:

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

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


✏️ 思路:
  1. 定义学生类
  2. 创建TreeSet集合对象,通过比较器排序进行排序
  3. 创建学生对象
  4. 把学生对象添加到集合
  5. 遍历集合

代码主体

TreeSetDemo类

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

/*
    需求:
        用TreeSet集合存储多个学生信息(姓名,语文成绩,数学成绩),并遍历该集合
        要求:按照总分从高到低出现
 */

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

        //创建TreeSet集合对象,通过比较器排序进行排序
        TreeSet<Student> st = new TreeSet<Student>(new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
//                int num = (s2.getChinese() + s2.getMath()) - (s1.getChinese() + s1.getMath());
                //主要条件
                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("大熊", 88, 90);
        Student s2 = new Student("静香", 95, 94);
        Student s3 = new Student("小夫", 80, 85);
        Student s4 = new Student("胖虎", 78, 60);
        Student s5 = new Student("老王", 88, 99);

        Student s6 = new Student("张三", 99, 88);
//        Student s7 = new Student("张三", 99, 88);
        Student s7 = new Student("李四", 99, 88);


        //把学生对象添加到集合
        st.add(s1);
        st.add(s2);
        st.add(s3);
        st.add(s4);
        st.add(s5);
        st.add(s6);
        st.add(s7);

        //遍历集合(增强for)
        for (Student s : st) {
            System.out.println(s.getName() + ":语文" + s.getChinese() + ",数学" + s.getMath() + ",总分:" + s.getSum());
        }
    }
}

Student类

/*
    学生类
 */

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.math;
    }

}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值