Map集合的第二种迭代--学习笔记

Map集合的第二种迭代,根据键值对对象,获取键和值--学习

 /**
     * Map集合的第二种迭代,根据键值对对象,获取键和值
     *  A:键值对对象找键和值思路:
     * 获取所有键值对对象的集合
     * 遍历键值对对象的集合,获取到每一个键值对对象
     * 根据键值对对象找键和值
     */
    @Test
    public void entrysetdaoe() {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("掌声", 162);
        map.put("美丽", 1272);
        map.put("故乡", 12287);
        map.put("清楚", 1272);

        //Map.Entry说明Entry是Map的内部接口,将键和值封装成了Entry对象,并存储在Set集合中
        Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
        //获取每一个对象
        Iterator<Map.Entry<String, Integer>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            //获取每一个Entry对象
            //获取每一个Entry对象
            Map.Entry<String, Integer> en = iterator.next();    //父类引用指向子类对象
            //Entry<String, Integer> en = it.next();    //直接获取的是子类对象
            String key = en.getKey();                   //根据键值对对象获取键
            Integer value = en.getValue();              //根据键值对对象获取值
            System.out.println(key + "=" + value);

        }

        //增强for循环
        System.out.println("================");
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey()+"==="+entry.getValue());
        }
    }

猜你喜欢

转载自blog.51cto.com/357712148/2308112