Map的迭代


迭代的方法有:
   keySet()
   values()
   entrySet()

1  集合遍历方法一:keySet() 

  结果:把Map集合中的所有键都保存到一个Set类型的集合对象中返回

1 Set<String> keys = map.keySet();
2     Iterator<String> it = keys.iterator();
3     while(it.hasNext()){
4         String key = it.next();
5         System.out.println("键: " + key + "   值: " + map.get(key));
6     }

缺点:只是返回了键,没有值。(即使 map.get(key) 给出了对应的值,但是该方法属于 Map ,不是 keySet 的)

思考:为什么要返回此映射中包含的键的 Set 视图?

  因为 key 不可重复!

2 集合遍历方法二:values() 

  结果:把所有的值存储到一个Collection集合中返回

1 Collection<String> keys = map.values();
2     Iterator<String> it = keys.iterator();
3     while(it.hasNext()){
4         System.out.println("值:"+ it.next());
5     }

缺点:只能返回集合中所有的值,没有键。

思考:能不能像方法一一样通过 get 方法得到对应的键?

  不能,只能通过键得到值,不能反过来。

3 集合遍历方法三:entrySet()

结果:返回此映射中包含的映射关系的 Set 视图

1 Set<Map.Entry<String, String>> entrys = map.entrySet();
2     Iterator<Map.Entry<String,String>> it = entrys.iterator();
3     while(it.hasNext()){
4         Map.Entry<String, String> entry = it.next();
5         System.out.println("键: " + entry.getKey() + "   值: " + entry.getValue());
6     }

思考:程序中 Entry<String, String> 写成这样也对,为什么要写成 Map.Entry<String, String> ?

  Entry 是 Map 的一个内部类,习惯上这样写。

推荐:entrySet()

示例 :

 1 public class Demo2 {
 2     public static void main(String[] args) {
 3         Map<String, String> map = new HashMap<String, String>();
 4         //添加方法
 5         map.put("汪峰", "章子怡");
 6         map.put("文章", "马伊琍");
 7         map.put("谢霆锋","张柏芝");
 8         map.put("成龙", "林凤娇");
 9         
10         //集合遍历方法一:keySet()  
11         //缺点:把Map集合中的所有键都保存到一个Set类型的集合对象中返回,所以只是返回了键,没有值
12     /*    Set<String> keys = map.keySet();
13         Iterator<String> it = keys.iterator();
14         while(it.hasNext()){
15             String key = it.next();
16             System.out.println("键: " + key + "   值: " + map.get(key));
17         }*/
18         
19         
20         //集合遍历方法二:values() 
21         //缺点:values() 把所有的值存储到一个Collection集合中返回,所以values方法只能返回集合中所有的值,没有键
22         /*Collection<String> keys = map.values();
23         Iterator<String> it = keys.iterator();
24         while(it.hasNext()){
25             System.out.println("值:"+ it.next());
26         }*/
27         
28         
29         //集合遍历方法三: entrySet() 
30         Set<Map.Entry<String, String>> entrys = map.entrySet();
31         Iterator<Map.Entry<String,String>> it = entrys.iterator();
32         while(it.hasNext()){
33             Map.Entry<String, String> entry = it.next();
34             System.out.println("键: " + entry.getKey() + "   值: " + entry.getValue());
35         }
原文地址:https://www.cnblogs.com/shadowdoor/p/6821343.html