一、需求:创建一个ArrayList
集合,存储三个元素,每一个元素都是HashMap,每一个HashMap的键和值都是String,并遍历
分析:
-
1.创建一个
ArrayList
集合 -
2.创建一个
HashMap
集合键和值都是String
-
3.将
HashMap
作为元素添加到ArrayList中 - 4.遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
public static void main(String[] args) { //创建ArrayList集合 ArrayList<HashMap<String,String>> al= new ArrayList<HashMap<String,String>>(); //创建HashMap集合 HashMap<String,String>hm= new HashMap<String,String>(); //添加键值对 hm.put( "01" , "张三" ); hm.put( "03" , "王五" ); hm.put( "02" , "李四" ); //创建HashMap集合 HashMap<String,String>hm1= new HashMap<String,String>(); //添加键值对 hm1.put( "05" , "张" ); hm1.put( "04" , "王" ); hm1.put( "07" , "李" ); //将HashMap放入ArrList中 al.add(hm); al.add(hm1); //遍历 for (HashMap<String,String> ss : al) { //内层依旧是HashMap的遍历方法 Set<String> key = ss.keySet(); for (String key1 : key) { String value = ss.get(key1); System.out.println(key1 + "," + value); } } } |
二、需求:创建一个HashMap集合,存储三个键值对元素,每一个键值对元素的键都是String,值是ArrayList
分析:
-
1.创建
HashMap
集合,键是String
,值是ArrayList
-
2.创建
ArrayList
集合并添加元素 -
3.将
ArrayList
作为值添加到HashMap集合中 - 4.遍历HashMap集合
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
public class HashMapInculdingArrayLis { public static void main(String[] args) { //创建HashMap集合 HashMap<String, ArrayList<String>> hm= new HashMap<String, ArrayList<String>>(); //创建ArrayList集合对象 ArrayList<String> al= new ArrayList<String>(); al.add( "张三" ); ArrayList<String> al1= new ArrayList<String>(); ArrayList<String> al2= new ArrayList<String>(); al2.add( "王五" ); al1.add( "李四" ); hm.put( "01" ,al); hm.put( "02" ,al1); hm.put( "03" ,al2); //遍历 Set<String>keySet =hm.keySet(); for (String key:keySet){ System.out.print(key+ "," ); ArrayList<String> strings = hm.get(key); for (String value:strings){ System.out.println(value); } } } } |
到此这篇关于Java案例分享-集合嵌套的文章就介绍到这了,更多相关Java集合嵌套内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/CYan521/p/16078929.html