Java基础知识--map集合的遍历方式

  Map.entrySet() 这个方法返回的是一个Set<Map.Entry<K,V>>,Map.Entry 是Map中的一个接口,他的用途是表示一个映射项(里面有Key和Value),而Set<Map.Entry<K,V>>表示一个映射项的Set。Map.Entry里有相应的getKey和getValue方法,即JavaBean,让我们能够从一个项中取出Key和Value。

  下面是遍历Map集合的四种方法:

 1 public class MapForeach {
 2     public static void main(String[] args) {
 3         Map<String,String> map = new HashMap<>();
 4         map.put("1","Java");
 5         map.put("2","python");
 6         map.put("3","c");
 7         map.put("4","php");
 8         System.out.println("使用四种方法遍历map集合:------");
 9         //第一种:普遍使用,二次取值
10         System.out.println("1.通过Map.keySet遍历key和value");
11         for (String key : map.keySet()){
12             System.out.println("key = "+key+" and value = "+map.get(key));
13         }
14 
15         System.out.println();
16         //第二种:使用iterator遍历
17         System.out.println("2.通过Map.entrySet使用iterator遍历key和value");
18         Iterator<Map.Entry<String,String>> iterator = map.entrySet().iterator();
19         while (iterator.hasNext()){
20             Map.Entry<String,String> entry = iterator.next();
21             System.out.println("key = "+entry.getKey()+" and value = "+entry.getValue());
22         }
23 
24         System.out.println();
25         //第三种:当map的容量比较大时,推荐使用
26         System.out.println("3.通过Map.entrySet遍历key和value");
27         for (Map.Entry<String,String> entry : map.entrySet()){
28             System.out.println("key = "+entry.getKey()+" and value="+entry.getValue());
29         }
30 
31         System.out.println();
32         //第四种:jdk8的foreach用法
33         System.out.println("4.通过jdk8提供的foreach方法遍历");
34         map.forEach((key,value)->{
35             System.out.println("key = "+key+" and value="+value);
36         });
37     }
38 }

遍历结果:

原文地址:https://www.cnblogs.com/wk-missQ1/p/13083319.html