Student.java
package yzhou.map; /**
* 学生类
*
*
* @author 洋
*
*/
public 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;
} }
ClassRoom.java
package yzhou.map; import java.util.ArrayList;
import java.util.List; /**
* 一个班级 多个学生
* @author 洋
*
*/
public class ClassRoom
{
private String no;
private List<Student> stuList;
private double total; public ClassRoom()
{
stuList = new ArrayList<Student>();
} public ClassRoom(String no)
{
this();
this.no = no;
} public ClassRoom(String no, List<Student> stuList, double total)
{
super();
this.no = no;
this.stuList = stuList;
this.total = total;
} public String getNo()
{
return no;
} public void setNo(String no)
{
this.no = no;
} 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;
} }
MapDemo03.java
package yzhou.map; import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set; /**
*
* 面向对象+分解存储
* @author 洋
*
*/
public class MapDemo03
{
public static void main(String[] args)
{
List<Student> stuList = exam();
Map<String, ClassRoom> map = count(stuList);
view(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);
} } /*
* 统计分析
* */
public static Map<String, ClassRoom> count(List<Student> list){
Map<String, ClassRoom> map = new HashMap<String,ClassRoom>();
//1.遍历
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;
} /*
* 模拟考试 测试数据到List 中
* */ public static List<Student> exam(){
List<Student> list = new ArrayList<Student>();
//存放学生成绩
list.add(new Student("yzhou01","a",80));
list.add(new Student("yzhou02","a",80));
list.add(new Student("yzhou03","a",80));
list.add(new Student("yzhou04","b",80));
list.add(new Student("yzhou05","b",80));
list.add(new Student("yzhou06","b",80));
return list;
}; }