定义一个九年级,年级里面有一班和二班。且有属于自己班的学生。
九年级
一班
001 张三
002 李四
二班
001 王五
002 马六
把同学都遍历出来
package demo; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.Map.Entry;; public class Demo { public static void main(String[] args) { //定义一班的集合 HashMap<String, String> class1 = new HashMap<String, String>(); //定义二班的集合 HashMap<String, String> class2 = new HashMap<String, String>(); //向班级存储学生 class1.put("001", "张三"); class1.put("002", "李四"); class2.put("001", "王五"); class2.put("002", "马六"); //定义grade容器 键是班级的名字 值是两个班级的容器 HashMap<String, HashMap<String, String>> grade = new HashMap<String, HashMap<String,String>>(); grade.put("class1", class1); grade.put("class2",class2); entrySet1(grade); } public static void entrySet1(HashMap<String, HashMap<String, String>> grade) { //entrySet():返回此映射中包含的映射关系的 Set 视图。 Set<Entry<String, HashMap<String, String>>> classNameSet = grade.entrySet(); //迭代Set集合 Iterator<Entry<String, HashMap<String, String>>> it = classNameSet.iterator(); while(it.hasNext()) { Entry<String, HashMap<String, String>> next = it.next(); //得到班级的名字 String classNameKey = next.getKey(); System.out.println(classNameKey); //得到具体每个班的map集合 HashMap<String, String> classMap = next.getValue(); Set<Entry<String, String>> classMapSet = classMap.entrySet(); Iterator<Entry<String, String>> studentIt = classMapSet.iterator(); while(studentIt.hasNext()) { Entry<String, String> studentEntry = studentIt.next(); //得到每个班级的同学的键 String numKey = studentEntry.getKey(); //得到每个班级同学键所对应的的值 String numValue = studentEntry.getValue(); System.out.println(numKey+" "+numValue); } } } }