//定义的学生类
import java.util.Map;
public class Student {
private String id;
private String name;
// private String courseName;
// private int score;
//把传统的定义属性操作转换未键值对的形式,String为课程名的数据类型,Integer为分数的包装类型
private Map<String,Integer> cs;
public Student() {
}
public Student(String id, String name, Map<String, Integer> cs) {
this.id = id;
this.name = name;
this.cs = cs;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, Integer> getCs() {
return cs;
}
public void setCs(Map<String, Integer> cs) {
this.cs = cs;
}
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Test {
public static void main(String[] args) {
ArrayList<Student> array=new ArrayList<Student>();
HashMap<String,Integer> map=new HashMap<>();
int sum=0,count=0,sum1=0,count1=0,sum2=0,count2=0,sum3=0,count3=0;
map.put("数据结构",80);
map.put("高数",85);
map.put("Java",100);
Student student=new Student("2019001","孙悟空",map);
array.add(student);
HashMap<String,Integer> map1=new HashMap<>();
map1.put("高数",60);
Student student1=new Student("2019002","猪八戒",map1);
array.add(student1);
HashMap<String,Integer> map2=new HashMap<>();
map2.put("高数",90);
map2.put("数据结构",98);
map2.put("java",94);
Student student2=new Student("2019003","唐僧",map2);
array.add(student2);
HashMap<String,Integer> map3=new HashMap<>();
map3.put("java",70);
map3.put("高数",78);
Student student3=new Student("2019004","沙和尚",map3);
array.add(student3)
//遍历ArrayList集合
***for(Student s:array){
System.out.print(s.getId()+","+s.getName()+",");
//获取键值对的集合
Map<String,Integer> m=s.getCs();//
//遍历Map
Set<Map.Entry<String, Integer>> entries = m.entrySet();
for(Map.Entry<String, Integer> p:entries){
String key=p.getKey();
Integer value=p.getValue();
System.out.print(key+":"+value+",");***
if(key.equals("数据结构")){
sum+=value;
count++;
}
if(key.equals("java")){
sum1+=value;
count1++;
}
if(key.equals("高数")){
sum2+=value;
count2++;
}
if(key.equals("高数")){
sum2+=value;
count2++;
}
}
System.out.println();
}
System.out.println("数据结构的平均分为:"+sum/count);
System.out.println("java的平均分为:"+sum1/count1);
System.out.println("高数的平均分为:"+sum2/count2);
}
}
其中的难点在于遍历各个科目的名称已经分数,通过先变量ArrayList集合中的每一个元素时嵌套遍历HashMap类中的每一个元素,在遍历HashMap的元素时,通过get()方法获取Student类中sc的值,此时sc的值是一个键值对的Map,把sc当作Map遍历即可。