当需要解决1:N问题时可以用到,包含知识点 迭代器 泛型
class Student{
private String name;
private String no;
private double 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;
}
}
class ClassRoom{
private String no;
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
private List<Student>stuList;//班级列表
private double total;
public ClassRoom(){
stuList=new ArrayList<Student>();
}
public ClassRoom(String no){
this();
this.no=no;
//stuList=new ArrayList<Student>();
}
public ClassRoom(String no,List<Student> stuList,double total){
super();
this.no=no;
this.stuList=stuList;
this.total=total;
}
public List<Student> getStuList() {
return stuList;
}
public void setStuList(List<Student> stuList) {
this.stuList = stuList;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
}
public class test1 {
//private static final List<Student> stuList = null;
public static void main(String[] args) {
//1.考试
List<Student>student=exam();
//2.分析成绩
Map<String,ClassRoom> map=count(student);
//3.查看成绩总分平均分
view(map);
}
public static List<Student> exam(){//模拟考试,测试数据到list
List<Student>list=new ArrayList<Student>();
list.add(new Student("战三","a",80));
list.add(new Student("李四","a",80));
list.add(new Student("王五","a",80));
list.add(new Student("赵六","b",80));
list.add(new Student("高企","b",80));
return list;
}
//统计分析 面向对象 分拣存储
public static Map<String,ClassRoom> count(List<Student> list){//将list集合放入map集合
Map<String,ClassRoom>map=new HashMap<String,ClassRoom>();
//遍历list
for(Student stu:list){
//分拣 查看是否存在该编号的班级
String no=stu.getNo();
double score=stu.getScore();
//如果不存在,创建班级
ClassRoom room=map.get(no);
if(null==room){
room=new ClassRoom(no);
map.put(no, room);
}
//存在放入学生
room.getStuList().add(stu);
room.setTotal(room.getTotal()+score);
}
return map;
}
//查看每个班级的总分和平均分 遍历map
public static void view(Map<String,ClassRoom>map){
Set<String>keys=map.keySet();
//获取迭代器对象
Iterator<String>keysIt=keys.iterator();
while(keysIt.hasNext()){
String no=keysIt.next();
ClassRoom room=map.get(no);
double total=room.getTotal();
double avg=total/room.getStuList().size();
System.out.println(no+"-->"+total+"--->"+avg);
}
}
}