package com.pkushutong.Collection;
/**
* 定义一个Student类,属性:名字、班号、成绩
* 现在将若干Student对象放入List,请统计出每个班级的总分和平均分,分别打印出来
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Test09 {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
exam(list);
//统计
Map<String,ClassRoom> rooms = new HashMap<String, ClassRoom>();
count(rooms,list);
//打印
printStudent(rooms);
}
//打印总分和平均分
public static void printStudent(Map<String,ClassRoom> rooms){
Set<Map.Entry<String, ClassRoom>> entrySet = rooms.entrySet();
Iterator<Map.Entry<String, ClassRoom>> it = entrySet.iterator();
while(it.hasNext()){
Map.Entry<String, ClassRoom> entry = it.next();
ClassRoom room = entry.getValue();
double avg = room.getTotal()/room.getStu().size();
System.out.println("班号为:"+room.getNo()+",总分:"+room.getTotal()+",平均分"+avg);
}
}
//统计分数
public static void count(Map<String,ClassRoom> rooms,List<Student> list){
for(Student stu : list){
String no = stu.getno();
double score = stu.getScore();
//根据班级编号 查看Map是否存在该班级
ClassRoom room = rooms.get(no);
if(room == null){ //第一次创建
room = new ClassRoom(no);
rooms.put(no, room);
}
//存储总分
room.setTotal(room.getTotal()+score);
room.getStu().add(stu); //加入学生
}
}
//现在将若干Student对象放入List
public static void exam(List<Student> list){
list.add(new Student("a","001",80));
list.add(new Student("b","002",85));
list.add(new Student("a","001",90));
list.add(new Student("d","004",85));
}
}
package com.pkushutong.Collection;
public class Student {
private String name;
private String no;
private double score;
@Override
public String toString() {
return "Student [name=" + name + ", no=" + no
+ ", score=" + score + "]";
}
public Student() {
}
public Student(String name, String no, double score) {
super();
this.name = name;
this.no = no;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getno() {
return no;
}
public void setno(String no) {
this.no = no;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
package com.pkushutong.Collection;
import java.util.ArrayList;
import java.util.List;
/**
* 班级
* @author dell
*
*/
public class ClassRoom {
private String no;
private List<Student> stu; //学生
private double total; //总分
public ClassRoom() {
stu = new ArrayList<Student>();
}
public ClassRoom(String no) {
this();
this.no = no;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
public List<Student> getStu() {
return stu;
}
public void setStu(List<Student> stu) {
this.stu = stu;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
}