创建一个ArrayList集合, 存储E个元素,每个元素都是HashMap, 每一个HashMap的键和值都是String, 并遍历。
//这里建了一个Student类,有姓名和年龄属性,由于较为简单,因此未放代码,下一题也是如此。 ArrayList<HashMap<Student,String>> list = new ArrayList<>(); //为了操作简单,只在list里写了两个HashMap,每个HashMap里也只写了三个。 HashMap<Student,String> hm1 = new HashMap<>(); Student s1 = new Student("孙悟空",23); Student s2 = new Student("贝吉塔",24); Student s3 = new Student("比克",13); hm1.put(s1,"地球"); hm1.put(s2,"撒亚星球"); hm1.put(s3,"那美克星球"); HashMap<Student,String> hm2 = new HashMap<>(); Student s4 = new Student("刘备",23); Student s5 = new Student("孙权",20); Student s6 = new Student("曹操",25); hm2.put(s4,"蜀国"); hm2.put(s5,"吴国"); hm2.put(s6,"魏国"); //最终把HashMap添加到list中 list.add(hm1); list.add(hm2); //开始遍历 for (HashMap<Student, String> hashMap : list) { //最外层是list,里面是HashMap,因此使用HashMap的key的集合keySet,再利用key对应value 的关系,遍历value Set<Student> keySet = hashMap.keySet(); for (Student key : keySet) { System.out.println("姓名:"+key.getName()+"年龄是:"+key.getAge()+"岁,是"+hashMap.get(key)+"人"); } }
创建一个HashMap集合, 存储E元素,值是ArrayList,用键给他们分类, 每一个ArrayList的键和值都是student, 并遍历。
本题和上一题类似,只是翻过进行嵌套。重点在于对集合的一层一层的剥离,理清嵌套的过程就可以完成对集合的遍历。
代码示例如下:
HashMap<String,ArrayList<Student>> hashMap = new HashMap<>(); ArrayList<Student> list1 = new ArrayList<>(); Student s1 = new Student("孙悟空",23); Student s2 = new Student("贝吉塔",24); Student s3 = new Student("比克",13); list1.add(s1); list1.add(s2); list1.add(s3); + ArrayList<Student> list2 = new ArrayList<>(); Student s4 = new Student("刘备",23); Student s5 = new Student("孙权",20); Student s6 = new Student("曹操",25); list2.add(s4); list2.add(s5); list2.add(s6); hashMap.put("龙珠",list1); hashMap.put("三国",list2); Set<String> keySet = hashMap.keySet(); for (String key : keySet) { ArrayList<Student> list = hashMap.get(key); for (Student stu : list) { System.out.println("是"+key+"中的人物"+"姓名是:"+stu.getName()+"年龄是:"+stu.getAge()); } }