Map集合遍历的两种方式

方式一.

 1 package cn.yschung.map;
 2 
 3 import java.util.Collection;
 4 import java.util.HashMap;
 5 import java.util.Map;
 6 import java.util.Set;
 7 
 8 public class MapDemo2 {
 9 
10     public static void main(String[] args) {
11         // TODO Auto-generated method stub
12         Map<String, String> map = new HashMap<String, String>();
13 
14         // 添加元素
15         map.put("dengchao", "sunli");
16         map.put("liukaiwei", "yangmi");
17         map.put("wenzhang", "yaodi");
18         // 获取集合中键的集合
19         // Set<E>
20         Set<String> set = map.keySet();
21         // 增强for遍历
22         for (String s : set) {
23             System.out.println(s);
24             // 根据键获取值<键,值>
25             System.out.println(map.get(s));
26             System.out.println("------------------");
27 
28         }
29         System.out.println("----------------------------------------------------------");
30         // 获取所有值的集合
31         Collection<String> c = map.values();
32         for (String ss : c) {
33             System.out.println(ss);
34         }
35     }
36 
37 }

方式二.

 1 package cn.yschung.map;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 import java.util.Set;
 6 
 7 public class MapDemo3 {
 8 
 9     public static void main(String[] args) {
10         // TODO Auto-generated method stub
11         Map<String, String> map = new HashMap<String, String>();
12 
13         // 添加元素
14         map.put("dengchao", "sunli");
15         map.put("liukaiwei", "yangmi");
16         map.put("wenzhang", "yaodi");
17         // 获取所有键值对对象的集合
18         Set<Map.Entry<String, String>> set = map.entrySet();
19         // 遍历键值对对象的集合
20         for (Map.Entry<String, String> me : set) {
21             System.out.println(me.getKey() + "--" + me.getValue());
22         }
23 
24     }
25 
26 }

猜你喜欢

转载自www.cnblogs.com/yschung/p/9364782.html