假如我有一个 List<Student> s,Student 有三个属性:name(名字),score(分数),rank(名次)。
我该怎么样根据 score 的大小给每个 s 的每一个 Student 进行排名(不排序,只是确定名次),然后把名次 存入 rank (1,2,3,4,…)中,相同 score 的算同一名次,score 越低名次越靠后
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class StudentSortDemo {
public static void main(String[] args) {
List<Student> studentList=new ArrayList<Student>();
studentList.add(new Student("小明", 85));
studentList.add(new Student("小花", 85));
studentList.add(new Student("小军", 100));
studentList.add(new Student("小强", 70));
studentList.add(new Student("小红", 85));
Comparator<Student> comparator=new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
if(o1.getSorce()<o2.getSorce()){
return 1;
}else if(o1.getSorce()==o2.getSorce()){
return 0;
}else{
return -1;
}
}
};
studentList.sort(comparator);
System.out.println(studentList);
for(int i=0,s=studentList.size();i<s;i++){
if(i>0 && studentList.get(i).getSorce()==studentList.get(i-1).getSorce()){
studentList.get(i).setRank(studentList.get(i-1).getRank());
}else{
studentList.get(i).setRank(i+1);
}
}
System.out.println(studentList);
}
}
class Student{
private String name;
private int sorce;
private int rank;
public Student(String name,int sorce){
this.name=name;
this.sorce=sorce;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSorce() {
return sorce;
}
public void setSorce(int sorce) {
this.sorce = sorce;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
@Override
public String toString() {
return getName()+" 分数:"+getSorce()+" 排名:"+getRank();
}
}
运行结果:
[小军 分数:100 排名:0, 小明 分数:85 排名:0, 小花 分数:85 排名:0, 小红 分数:85 排名:0, 小强 分数:70 排名:0]
[小军 分数:100 排名:1, 小明 分数:85 排名:2, 小花 分数:85 排名:2, 小红 分数:85 排名:2, 小强 分数:70 排名:5]
转载请注明:前端收藏 » JAVA中通过List实现学生成绩名次排名