Java基础知识强化之集合框架笔记63:Map集合之HashMap嵌套ArrayList

1. ArrayList集合嵌套HashMap集合并遍历。

需求:假设ArrayList集合的元素是HashMap。有3个。每一个HashMap集合的键和值都是字符串。元素我已经完成,请遍历。

结果:

   三国演义
      吕布
      周瑜

   笑傲江湖
      令狐冲
      林平之

   神雕侠侣
      郭靖
      杨过

2. 代码示例:

 1 package cn.itcast_05;
 2 
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.Set;
 6 
 7 /*
 8  *需求:
 9  *假设HashMap集合的元素是ArrayList。有3个。
10  *每一个ArrayList集合的值是字符串。
11  *元素我已经完成,请遍历。
12  *结果:
13  *         三国演义
14  *             吕布
15  *             周瑜
16  *         笑傲江湖
17  *             令狐冲
18  *             林平之
19  *         神雕侠侣
20  *             郭靖
21  *             杨过  
22  */
23 public class HashMapIncludeArrayListDemo {
24     public static void main(String[] args) {
25         // 创建集合对象
26         HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
27 
28         // 创建元素集合1
29         ArrayList<String> array1 = new ArrayList<String>();
30         array1.add("吕布");
31         array1.add("周瑜");
32         hm.put("三国演义", array1);
33 
34         // 创建元素集合2
35         ArrayList<String> array2 = new ArrayList<String>();
36         array2.add("令狐冲");
37         array2.add("林平之");
38         hm.put("笑傲江湖", array2);
39 
40         // 创建元素集合3
41         ArrayList<String> array3 = new ArrayList<String>();
42         array3.add("郭靖");
43         array3.add("杨过");
44         hm.put("神雕侠侣", array3);
45         
46         //遍历集合
47         Set<String> set = hm.keySet();
48         for(String key : set){
49             System.out.println(key);
50             ArrayList<String> value = hm.get(key);
51             for(String s : value){
52                 System.out.println("	"+s);
53             }
54         }
55     }
56 }

运行效果,如下:

 

原文地址:https://www.cnblogs.com/hebao0514/p/4865872.html