JavaSE-16.1.3【案例-集合嵌套之ArrayList嵌套HashMap和HashMap嵌套ArrayList】

 1 package day7.lesson1.anli3;
 2 
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.Set;
 6 
 7 /*
 8 1.5.3 案例-集合嵌套之ArrayList嵌套HashMap(ArrayList集合存储HashMap元素并遍历)
 9     创建一个ArrayList集合,存储三个元素,每一个元素都是HashMap
10     每一个HashMap的键和值都是String,并遍历。
11  */
12 public class ArrayListIncludeHashMapDemo {
13     public static void main(String[] args) {
14         ArrayList< HashMap<String, String> > arrayList = new ArrayList<>();
15 
16         HashMap<String, String> hm1 = new HashMap<>();
17         hm1.put("孙策", "大乔");
18         hm1.put("周瑜", "小乔");
19         arrayList.add(hm1);
20 
21         HashMap<String, String> hm2 = new HashMap<>();
22         hm2.put("郭靖", "黄蓉");
23         hm2.put("杨过", "小龙女");
24         arrayList.add(hm2);
25 
26         HashMap<String, String> hm3 = new HashMap<>();
27         hm3.put("令狐冲", "任盈盈");
28         hm3.put("林平之", "岳灵珊");
29         arrayList.add(hm3);
30 
31         for (HashMap<String, String> hm: arrayList){
32             Set<String> keySet = hm.keySet();
33             for (String key: keySet){
34                 String value = hm.get(key);
35                 System.out.println(key + "," + value);
36             }
37         }
38     }
39 }
 1 package day7.lesson1.anli4;
 2 
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.Set;
 6 
 7 /*
 8 1.5.4 案例-集合嵌套之HashMap嵌套ArrayList(HashMap集合存储ArrayList元素并遍历)
 9     创建一个HashMap集合,存储三个键值对元素,每一个键值对元素的键是String,值是ArrayList
10     每一个ArrayList的元素是String,并遍历。
11  */
12 public class HashMapIncludeArrayListDemo {
13     public static void main(String[] args) {
14         HashMap< String, ArrayList<String> > hashMap = new HashMap<>();
15 
16         ArrayList<String> al1 = new ArrayList<>();
17         al1.add("诸葛亮");
18         al1.add("赵云");
19         hashMap.put("三国演义", al1);
20 
21         ArrayList<String> al2 = new ArrayList<>();
22         al2.add("孙悟空");
23         al2.add("唐僧");
24         hashMap.put("西游记", al2);
25 
26         ArrayList<String> al3 = new ArrayList<>();
27         al3.add("武松");
28         al3.add("鲁智深");
29         hashMap.put("水浒传", al3);
30 
31         Set<String> keySet = hashMap.keySet();
32         for (String key: keySet){
33             System.out.println(key + ":");
34             ArrayList<String> value = hashMap.get(key);
35             for (String s: value){
36                 System.out.println("\t" + s);
37             }
38         }
39     }
40 }

 

posted @ 2021-06-02 16:27  yub4by  阅读(71)  评论(0编辑  收藏  举报