HashMap分拣思想

/**
 * 定义一个Student类  现在将若干个Student对象放入List中查看每个班的总分和平均分
 * 方案:面向对象+分拣存储(一对多的问题1:N)
 * @author Administrator
 *
 */
public class MapDemo03 {
public static void main(String[] args) {
//1.考试
List<Student> stuList = exam();
//2.分析成绩

Map<String,ClassRoom> map = count(stuList);

//3.查看成绩(总分 平均分)
View(map);
}
/**
* 查看每个班的总分和平均分  遍历map
*/

public static void View(Map<String,ClassRoom> map) {
Set<String> keys = map.keySet(); //获取map中的键 保存到Set容器中
/**
* 利用迭代器遍历keys 
*/
//首先后去迭代器对象
Iterator<String> iterator = keys.iterator();

//先判断
while(iterator.hasNext()) {
//在获取
String no = iterator.next();

//获map 中键为no的值 返回的是一个ClassRoom对象
ClassRoom room = map.get(no);
//查看总分 计算平均分
double total = room.getTotal();

double avg = total/room.getStuList().size();

System.out.println(no + "-->" + total + "-->" + avg);

}
}

/**
* 统计分析
* 1.面向对象
* 2.分拣存储
*/

public static Map<String,ClassRoom> count(List<Student> list){
Map<String,ClassRoom> map  = new HashMap<String,ClassRoom>();
//1.遍历List
for(Student stu:list) {
//2.分拣  查看是否存在该编号的班级 
String no = stu.getNo();//班级编号
double score = stu.getScore();//分数
ClassRoom room = map.get(no); //获得map中的键 返回值
// 如果不存在 创建班级
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("老配","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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值