需求:用TreeSet集合存储多个学生信息(姓名,语文成绩,数学成绩),并遍历该集合
要求:按照总分从高到低
思路:
1、定义学生类
2、创建TreeSet对象,通过比较器对象进行排序
3、创建学生类
4、把学生对象添加到集合
5、遍历集合
代码示例
public static void main(String[] args) {
//创建集合对象
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
//主要条件:总分
int num = (s2.getMath() + s2.getChinese()) - (s1.getChinese() + s1.getMath());
//次要条件1:语文成绩
int num2 = num == 0 ? s2.getChinese() - s1.getChinese() : num;
//次要条件2:姓名的顺序
int num3 = num2 == 0 ? s1.getName().compareTo(s2.getName()) : num2;
return num3;
}
});
//创建学生类
Student s1 = new Student("张三", 95, 83);
Student s2 = new Student("李四", 80, 89);
Student s3 = new Student("吴五", 92, 90);
Student s4 = new Student("陈六", 95, 98);
Student s5 = new Student("赵七", 78, 88);
Student s6 = new Student("王八", 66, 69);
Student s7 = new Student("林九", 65, 70);
//向集合添加对象
ts.add(s1);
ts.add(s2);
ts.add(s3);
ts.add(s4);
ts.add(s5);
ts.add(s6);
ts.add(s7);
//遍历集合
for (Student s : ts) {
System.out.println(s.getName()+","+s.getChinese()+","+s.getMath()+",总分:"+(s.getMath()+s.getChinese()));
}
}
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;
}
}