Map的四种遍历方式

首先说一下Map.entrySet()这个方法,Map.entrySet()返回的是一个Set<Map.Entry<K,V>>,Map.Entry是Map中的一个接口,Map.Entry是Map中的一个映射项(key,value),而Set<Map.Entry<K,V>>是映射项的Set集合.Map.Entry里有相应的getKey和getValue方法,即javaBean,让我们能够从一个项中取出key和value.

下面用代码写一下Map遍历的四种方式

public static void main(){

  Map<String,String> map = new HashMap();

  map.put("1","value1");

  map.put("2"."value2");

  map.put("3","value3");

}

1.利用map.keySet()方法获取所有key的集合,然后通过map.get(key)获取value

for(String key : map.keySet()){

  System.out.println(map.get(key));

}

2.利用Map.entrySet()获取Set遍历,然后利用Iterator()遍历进行获取

Iterator<Map.Entry<String,String>> it = map.entrySet().iterator();

while(it.hasNext()){

  Map.Entry<String,String> entry = it.next();

  System.out.println(entry.getKey() + ":" + entry.getValue());

}

3.这种方法是推荐的(网上说适合容量较大时的遍历,原因:只遍历的一遍就把所需的key以及value的值放入entrySet,而keySet需要遍历两遍,第一遍是获取所有key,第二遍是get(key)遍历一遍)

for(Map.entrySet<String,String> entry:map.entrySet()){

  System.out.println(entry.getKey() + ":" + entry.getValue());

}

4.利用map.values() 遍历所有value的值,但是不能遍历到key

for(String value : map.values()){

  System.out.println(value);

}

原文地址:https://www.cnblogs.com/coder-who/p/12058746.html