需求:用TreeSet集合存储多个学生信息(姓名,语文成绩,数学成绩),并遍历该集合
要求:按照总分从高到低出现
先定义一个学生类
package ysy11;
public class Student {
private String name;
private int ChineseScore;
private int MathScore;
public Student() {
}
public Student(String name, int chineseScore, int mathScore) {
this.name = name;
ChineseScore = chineseScore;
MathScore = mathScore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChineseScore() {
return ChineseScore;
}
public void setChineseScore(int chineseScore) {
ChineseScore = chineseScore;
}
public int getMathScore() {
return MathScore;
}
public void setMathScore(int mathScore) {
MathScore = mathScore;
}
//创建一个总分
public int getSum(){
return this.ChineseScore+this.MathScore;
}
}
测试类
注意主要条件和次要条件
package ysy11;
import java.util.Comparator;
import java.util.TreeSet;
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Student> ts=new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
//主要条件:比较两个人的总分this--s1,s--s2按从高往低排名
int num=s2.getSum()-s1.getSum();
/*
次要条件1:如果总分相同,即num==0,则比较语文分数
按语文分数从高往低排名
*/
int num2=num==0?s2.getChineseScore()- s1.getChineseScore():num;
/*
次要条件2:如果总分相同,且各科分数都相同,则比较姓名
姓名不同按字母排序
*/
int num3=num2==0?s1.getName().compareTo(s2.getName()):num2;
return num3;
}
});
//创建学生对象
Student s1 =new Student("西施",87,68);
Student s2 =new Student("貂蝉",78,83);
Student s3 =new Student("杨玉环",66,75);
Student s4 =new Student("王昭君",76,65);
Student s5 =new Student("小鱼",78,83);
//把学生添加到集合
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.getChineseScore()+",数学成绩是"+s.getMathScore()+",总分是"+s.getSum());
}
}
}