以下供参考:package com.test;
public class Student {
/**
* id
*/
private String id;
/**
* 学号
*/
private String code;
/**
* 姓名
*/
private String name;
/**
* 成绩
*/
private float score;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public Student(String id, String code, String name, float score) {
super();
this.id = id;
this.code = code;
this.name = name;
this.score = score;
}
public Student() {
super();
}
}
package com.test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
Student a = new Student("1", "001", "张三", 90.1f);
Student b = new Student("2", "002", "李四", 70.2f);
Student c = new Student("3", "003", "王五", 80.3f);
Student d = new Student("4", "004", "赵六", 60.4f);
Student e = new Student("5", "005", "钱七", 50.5f);
List list = new ArrayList();
list.add(a);
list.add(b);
list.add(c);
list.add(d);
list.add(e);
float avg = getAvg(list);
System.out.println("平均分为: " + avg);
int sort = getSort(list, "003");
System.out.println("排名为: " + sort);
}
/**
* 根据学号查询该学生的排名
* @param list
* @param studentCode
* @return
*/
private static int getSort(List list, String studentCode) {
//因为是排名,所以降序排序
Collections.sort(list, new Comparator() {
@Override
public int compare(Student o1, Student o2) {
if (o1.getScore() > o2.getScore()) {
return -1;
} else if (o1.getScore() == o2.getScore()) {
return 0;
} else {
return 1;
}
}
});
int sort = 0;
//因为list从0开始,所以要+1
for (int i = 0; i
if(list.get(i).getCode().equals(studentCode)){
sort = i+1;
break;
}
}
return sort;
}
/**
* 传入list查询平均分
* @param list
* @return
*/
private static float getAvg(List list) {
int count = list.size();
float totalScore = 0f;
for (Student student : list) {
totalScore += student.getScore();
}
float avg = totalScore / count;
return avg;
}
}
输出结果:平均分为: 70.3
排名为: 2