时间:2022-11-18 10:09:26 | 栏目:JAVA代码 | 点击:次
一、需求:创建一个ArrayList
集合,存储三个元素,每一个元素都是HashMap,每一个HashMap的键和值都是String,并遍历
分析:
ArrayList
集合HashMap
集合键和值都是String
HashMap
作为元素添加到ArrayList中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
分析:
HashMap
集合,键是String
,值是ArrayList
ArrayList
集合并添加元素ArrayList
作为值添加到HashMap集合中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); } } } }