JAVA集合练习——集合的嵌套
2021/4/27 22:26:26
本文主要是介绍JAVA集合练习——集合的嵌套,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
问题一
创建一个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()); } }
这篇关于JAVA集合练习——集合的嵌套的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)
- 2024-05-30【Java】百万数据excel导出功能如何实现
- 2024-05-30我们小公司,哪像华为一样,用得上IPD(集成产品开发)?