案例:集合嵌套之HashMap嵌套ArrayList

9ab6281437a15890e569ceb9833e781c.png

public class HashMapDemo {
    public static void main(String[] args) {
        //创建HashMap集合
        HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();

        //创建ArrayList集合,并添加元素
        ArrayList<String> sgyy = new ArrayList<String>();
        sgyy.add("诸葛亮");
        sgyy.add("赵云");
        //把ArrayList作为元素添加到HashMap集合
        hm.put("三国演义", sgyy);

        //创建ArrayList集合,并添加元素
        ArrayList<String> xyj = new ArrayList<String>();
        xyj.add("唐僧");
        xyj.add("孙悟空");
        //把ArrayList作为元素添加到HashMap集合
        hm.put("西游记", xyj);

        //创建ArrayList集合,并添加元素
        ArrayList<String> shz = new ArrayList<String>();
        shz.add("武松");
        shz.add("鲁智深");
        //把ArrayList作为元素添加到HashMap集合
        hm.put("水浒传", shz);

        //遍历HashMap集合
        /*
            ArrayList集合作为HashMap集合的元素,首先先遍历HashMap集合获取键集合,根据键来获取值
            而值是由ArrayList集合作为元素存在的,所以还需要通过遍历ArrayList集合来获取每一个元素(值)
         */
        Set<String> keySet = hm.keySet();
        for (String key : keySet) {
            System.out.println(key);
            ArrayList<String> value = hm.get(key);
            for (String s : value) {
                System.out.println("\t" + s);
            }
        }
    }
}

运行结果:

猜你喜欢

转载自www.cnblogs.com/pxy-1999/p/12675441.html