首页 > 代码库 > 遍历Map集合的几种方式

遍历Map集合的几种方式

 1 import java.util.HashMap;
 2 import java.util.Iterator;
 3 import java.util.Map;
 4 import java.util.Map.Entry;
 5 
 6 /**
 7  * <p>遍历Map集合</p>
 8  * @author:774346810@qq.com
 9  * @date:2017-5-30
10  */
11 public class Test {
12     public static void main(String[] args) {
13         Map<String, String> map = new HashMap<String, String>();
14         map.put("username", "yujiwei");
15         map.put("password", "12345");
16         map.put("address", "hangzhou");
17         map.put("love", "编程");
18         //1.获取所有的key
19         for(String key : map.keySet()){//返回的是map的key值
20             String value = http://www.mamicode.com/map.get(key);//通过key取value
21             System.out.println("key = " + key + ",value = "http://www.mamicode.com/+ value);
22         }
23         
24         System.out.println("----------------------------------");
25         
26         //2.通过map.entrySet的iterator来遍历Map集合
27         Iterator<Entry<String, String>> it = map.entrySet().iterator();
28         while(it.hasNext()){
29             Entry<String, String> entry = it.next();
30             System.out.println("key= " + entry.getKey() + " and value= "http://www.mamicode.com/+ entry.getValue());
31         }
32         
33         System.out.println("----------------------------------");
34         
35         //3.通过Map.Entry来遍历Map集合
36         for(Map.Entry<String, String> entry : map.entrySet()){
37             System.out.println("key= " + entry.getKey() + " and value= "http://www.mamicode.com/+ entry.getValue());
38         }
39     }
40 }

 

遍历Map集合的几种方式