成績排序
-
需求:
用TreeSet集合存儲多個學生資訊(姓名,國文成績,數學成績,并周遊該集合)
-
要求:
按照總分從高到低出現
public class Student {
private String name;
private int chinese;
private int math;
public Student() {}
public Student(String name, int chinese, int math) {
super();
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.getChinese()+this.getMath();
}
}
public class TreeSetTest {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
//主要條件
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("1小明", 98, 99);
Student s2 = new Student("2小紅", 78, 79);
Student s3 = new Student("3小藍", 88, 89);
Student s4 = new Student("4小黑", 87, 90);
Student s5 = new Student("5小白", 87, 90);
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());
}
}
}