Java-集合框架-map4(巢狀集合)
阿新 • • 發佈:2020-08-10
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 staticvoid 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 = newHashMap<>(); 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()); } } } }
實際上也就是多重的集合取數