package cn.burce.HashMap; import java.util.HashMap; public class MapDemo3 { // 神奇小学 // 一年级 // 101 小米 102 小明 // 二年级 // 201 大米 202 大明 public static void main(String[] args) { fun(); System.out.println("----------------------------------"); fun1(); } public static void fun() { HashMap<String, String> one = new HashMap<>(); HashMap<String, String> two = new HashMap<>(); one.put("101", "小米"); one.put("102", "小明"); two.put("201", "大米"); two.put("202", "大明"); HashMap<String, HashMap<String, String>> school = new HashMap<>(); school.put("一年级", one); school.put("二年级", two); System.out.println(school + "大大主键"); Set<String> set = new HashSet<>(); set = school.keySet();// 将键存到set集合,键是一个String Iterator<String> it = set.iterator();// 通过Iterator去遍历这组字符串 while (it.hasNext()) { String str = it.next(); System.out.println(str + "大主键"); HashMap<String, String> p1 = school.get(str); System.out.println(p1 + "嵌套集合"); Set<String> set1 = p1.keySet();// 将键存到set集合,键是一个String System.out.println("set1是"+set1); // 增强for for (String s : set1) { System.out.println(str+"..."+s+"..."+p1.get(s)); } } } public static void fun1() { HashMap<String, String> thr = new HashMap<>(); HashMap<String, String> four = new HashMap<>(); thr.put("301", "豪情天下"); thr.put("302", "光阴似箭"); four.put("401", "龙腾万里"); four.put("402", "无印之水"); HashMap<String, HashMap<String, String>> school = new HashMap<>(); school.put("三年级", thr); school.put("四年级", four); System.out.println(school + "大大主键"); // 将map中的方法 entrySet取出映射关系,存到Set集合里Set<K,V> Set<Map.Entry<String, HashMap<String, String>>> set = school.entrySet(); Iterator<Map.Entry<String, HashMap<String, String>>> it = set.iterator(); while (it.hasNext()) {// 获取出set集合的元素,这里仍旧是map结构 Map.Entry<String, HashMap<String, String>> entry = it.next(); // 根据getKey和getValue取出键值 String s = entry.getKey(); // System.out.println(s); HashMap<String, String> zclass = entry.getValue(); Set<Map.Entry<String, String>> set1 = zclass.entrySet(); // 增强for for (Map.Entry<String, String> entry2 : set1) { System.out.println(s + "..." + entry2.getKey() + "..." + entry2.getValue()); } } } }
实际上也就是多重的集合取数