遍历Map的key集,value集,key-value集,使用上泛型

在这里插入图片描述

使用keySet( )方法返回的key集构成的集合是Set:无序的、不可重复的。

@Test
    public void test1(){
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("fanlihui",24);
        map.put("yuanhongwei",25);
        map.put("hahaah",78);
        Set<String> keyset = map.keySet();
        //遍历Map中的key集,使用增强for循环
        for(String s:keyset){
            System.out.println(s);
        }
    }   

调用values()方法返回的value集构成的集合是Collection:无序的、可以重复的。

 @Test
    public void test2(){
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("fanlihui",24);
        map.put("yuanhongwei",25);
        map.put("hahaah",78);
        Collection<Integer> value = map.values();
        //使用迭代器遍历Map中的value
        Iterator<Integer> iterator = value.iterator();
        while(iterator.hasNext()){
            Integer integer = iterator.next();
            System.out.println(integer);
        }
    }

调用entrySet()方法返回的key-value集构成的集合是Set:无序的、不可重复的

@Test
    public void test3(){
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("fanlihui",24);
        map.put("yuanhongwei",25);
        map.put("hahaah",78);
        Set<Map.Entry<String,Integer>> entry= map.entrySet();
        Iterator<Map.Entry<String, Integer>> iterator = entry.iterator();
        while(iterator.hasNext()){
            Map.Entry<String, Integer> entry1 = iterator.next();
            System.out.println(entry1);
        }
    }

}

版权声明:本文为weixin_45925146原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。