Set集合 TreeSet 案例 成绩排序
知止自律打卡-微信小程序APP
一款微信自律打卡小程序,支持自定义打卡项目、习惯记录、项目日记、专注计时与数据统计。自律打卡、学习打卡、读书打卡、健身打卡、运动打卡、减肥打卡、戒色打卡、养生打卡、戒烟、戒酒、戒熬夜等多种场景。万能打卡模板自由创建。可自定义每日打卡目标,记录习惯连续天数,可视化追踪成长进度。
了解产品详情 →
微信搜索「知止自律打卡」
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());
}
}
}
标签: