Map的嵌套 练习
利用迭代和增强for循环的两种方式实现如下效果
package cn.ccc;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class two {
public static void main(String[] args) {
//定义java班的集合
HashMap<String, String> java = new HashMap<String, String>();
//向班级存储学生
java.put("20190322", "第一名");
java.put("20190323", "第二名");
java.put("20190324", "第三名");
//定义Dhoop班的集合
HashMap<String, String> Dhoop = new HashMap<String,String>();
//向Dhoop班级存储学生
Dhoop.put("20190401", "第一名");
Dhoop.put("20190402", "第二名");
Dhoop.put("20190403", "第三名");
//定义集合aa容器 键是班级的名字 值是两个班级的容器
HashMap<String, HashMap<String, String>> aa = new HashMap<String,HashMap<String, String>>();
aa.put("java班", java);
aa.put("Dhoop班", Dhoop);
EntrySet(aa);
}
private static void EntrySet(HashMap<String, HashMap<String, String>> aa) {
//调用集合aa的方法entrySet将aa集合的键封装到Set集合中
Set<Entry<String, HashMap<String, String>>> classenset = aa.entrySet();
//迭代Set集合
Iterator<Entry<String, HashMap<String, String>>> it = classenset.iterator();
while(it.hasNext()){
Entry<String, HashMap<String, String>> classnext = it.next();
String classkey = classnext.getKey();
HashMap<String, String> classvalue = classnext.getValue();
System.out.println(classkey);
///
Set<Entry<String, String>> studentset = classvalue.entrySet();
Iterator<Entry<String, String>> studentit = studentset.iterator();
while(studentit.hasNext()){
Entry<String, String> studentnext = studentit.next();
String numk = studentnext.getKey();
String numv = studentnext.getValue();
System.out.println(numk+" "+numv);
}
}
System.out.println(".........................................................");
//增强for循环
Set<Entry<String, HashMap<String, String>>> forclassset = aa.entrySet();
for(Entry<String, HashMap<String, String>> i:forclassset){
String classk = i.getKey();
HashMap<String, String> classv = i.getValue();
Set<Entry<String, String>> forstudentset = classv.entrySet();
System.out.println(classk);
for(Entry<String, String> j:forstudentset){
String numkey = j.getKey();
String numvalue = j.getValue();
System.out.println(numkey+" "+numvalue);
}
}
}
}