HashMap集合存储ArraysList元素并遍历
HashMap集合存储ArraysList元素并遍历
-
需求:创建一个HashMap集合,存储三个键值对元素,每一个键值对元素的键是String,值是ArraysList,每一个ArraysList类的元素是String,并遍历
-
思路:
创建HashMap集合
创建ArraysList集合,并添加键值对元素
把ArrayList作为元素添加到HashMap集合中集合中
遍历HashMap集合中 -
例如:在集合中遍历出三国演义,水浒传,西游记的其中两名人物
以代码内容形式讲解
package Demo;import java.util.*;public class Demo { public static void main(String[] args) { //创建HashMap集合 HashMap<String,ArrayList<String>> s = new HashMap<>(); //创建ArraysList集合 ArrayList<String> strings = new ArrayList<>(); strings.add("孙悟空"); strings.add("唐僧"); s.put("西游记",strings); ArrayList<String> strings2 = new ArrayList<>(); strings2.add("宋江"); strings2.add("李逵"); s.put("水浒传",strings2); ArrayList<String> strings3 = new ArrayList<>(); strings3.add("赵云"); strings3.add("关于"); s.put("三国演义",strings3); //遍历元素 这里我们可以采取根据键遍历值 Set<String> strings1 = s.keySet(); for (String string : strings1){ ArrayList<String> strings4 = s.get(string); System.out.println(string); for (String x:strings4) { System.out.println("\t"+x); } } }}
输出的内容
水浒传
宋江
李逵
三国演义
赵云
关于
西游记
孙悟空
唐僧