map的4种遍历方式

MAP是一个我们日常写程序用得比较多的集合,因为他的键值映射的缘故,我们能清晰的定位到某一个位置。

我根据网上资料,简单总结了遍历map的四种用法

3种foreach循环,1种while循环

代码如下:

public static void  main(String [] args)

{

    Map<String,String>testMap=new HashMap<String,String>();
    testMap.put("key1","value1");
    testMap.put("key2","value2");
    testMap.put("key3","value3");

    System.out.println("map遍历测试1");
    for(String key:testMap.keySet()){
        System.out.println("key:"+key+"/value:"+testMap.get(key));
    }

    System.out.println("map遍历测试2(只遍历值)");
    for (String value:testMap.values()){
        System.out.println("value:"+value);
    }

    System.out.println("map遍历测试3(用于大容量)");
    for (Map.Entry<String,String>entry:testMap.entrySet()){
        System.out.println("key:"+entry.getKey()+"value:"+entry.getValue());
    }

    System.out.println("map遍历4(迭代器)");
    Iterator<Map.Entry<String,String>>iterator=testMap.entrySet().iterator();
   while ( iterator.hasNext()){
       Map.Entry<String,String>entry= iterator.next();
       System.out.println("key:"+entry.getKey()+"/value:"+entry.getValue());
   }
}

方法1,方法2分别用foreach循环遍历了map中的键和值,由于方法1是遍历键,我们可以通过键来获取到值
方法2直接遍历值,得到的是数据,没有什么能与之映射。
方法3、方法4都是通过Map的Entry入口拿到key、value,只是3、4的遍历方式不一样,4则是通过迭代器遍历,如果map有值
hasNext()方法为true,继续执行while循环。


猜你喜欢

转载自blog.csdn.net/dwj1250254648/article/details/78889276