java 18


  HashMap嵌套HashMap

  动物
    犬类
        哈士奇   2
        萨摩耶   1
    猫类
       波斯猫     2
       加菲猫     3

先存储元素,然后遍历元素

 1 package map_son;
 2 
 3 import java.util.HashMap;
 4 import java.util.Set;
 5 
 6 
 7 public class MapMapDemo {
 8 
 9     public static void main(String[] args) {
10         
11         //首先定义总的集合,动物
12         HashMap<String ,HashMap<String,Integer>> animal = new HashMap<String,HashMap<String,Integer>>();
13         
14         //定义被嵌套的集合:犬类
15         HashMap<String , Integer> dog = new HashMap<String , Integer>();
16         
17         //添加犬类的元素到狗类集合中
18         dog.put("哈士奇",2);
19         dog.put("萨摩耶",1);
20         
21         //把狗类添加进去动物类中
22         animal.put("犬类",dog);
23         
24         //定义被嵌套的集合:猫类
25         HashMap<String,Integer> cat = new HashMap<String,Integer>();
26         
27         //添加猫类的元素到猫类集合中
28         cat.put("波斯猫",2);
29         cat.put("加菲猫",3);
30         
31         //添加猫类到动物类中
32         animal.put("猫类",cat);
33         
34         //进行动物类的遍历
35         //获取动物类的键集合
36         Set <String> animalset = animal.keySet();//键是犬类,猫类
37         
38         //遍历键集合
39         for(String animalkey : animalset){ 
40             
41             //获取键对应的值 : HashMap<String,Integer>
42             HashMap<String,Integer> two = animal.get(animalkey);
43             //对这个集合进行遍历
44             //获取这个集合的键集合
45             Set <String> str = two.keySet();
46             for(String setkey : str){
47                 //获取键对应 的值
48                 two.get(setkey);
49                 //输出
50                 System.out.println(animalkey + two );
51             }
52         }
53         
54     }
55 
56 }
何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
原文地址:https://www.cnblogs.com/LZL-student/p/5907266.html