问题- 我有一个学生班,它包含姓名、学号、三个科目分数 m1、m2、m3 和总分。如果两个或更多学生的分数相等,我需要根据他们的总分对学生对象进行排序,然后根据他们的姓名对其进行排序。注意- 我必须用谷歌搜索它,但在 stackoverflow 问题中没有得到预期的解决方案,每个问题都使用 Comparable 和 Comparator 接口。
我创建了 Studnt 类
public class Student {
private String name;
private Integer rollNumber;
private int m1;
private int m2;
private int m3;
private int totMarks;
//Getter setter
}
主类
public class StudentData {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enetr the number of Student");
int totalStudent = sc.nextInt();
Map<Integer,Student> map = new TreeMap<Integer,Student>();
for(int i =0;i<totalStudent;i++) {
Student ss = new Student();
System.out.println("Enter the Student roll number");
ss.setRollNumber(sc.nextInt());
System.out.println("Enter the Student Name");
ss.setName(sc.next());
System.out.println("Enter the m1 marks ");
ss.setM1(sc.nextInt());
System.out.println("Enetr the m2 marks ");
ss.setM2(sc.nextInt());
System.out.println("Enter the m3 marks ");
ss.setM3(sc.nextInt());
ss.setTotMarks(ss.getM1()+ss.getM2()+ss.getM3());
map.put(ss.getTotMarks(),ss);
ss=null;
}
//stdList.forEach(System.out::print);
for(Map.Entry<Integer,Student> m :map.entrySet()) {
System.out.println(m);
}
}
}
实际上,我正在使用 TreeMap 它按键对值进行排序(总分是我的 TreeMap 中的键)。但两个或更多学生的分数相同。然后旧学生对象(值)被新学生替换,因为 Key 不允许重复
输出
6=学生 [姓名=ved, rollNumber=12, m1=2, m2=2, m3=2, totMarks=6]
9=学生 [姓名=prakash, rollNumber=56, m1=3, m2=3, m3=3, totMarks=9]
地图中存储的唯一唯一 totMarks
UYOU
胡说叔叔
翻过高山走不出你
相关分类