1. 程式人生 > >遍歷Map集合的幾種方式

遍歷Map集合的幾種方式

set password stat class ati put 獲取 map hashmap

 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:[email protected]
 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 = map.get(key);//
通過key取value 21 System.out.println("key = " + key + ",value = " + 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= " + 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= "+ entry.getValue()); 38 } 39 } 40 }

遍歷Map集合的幾種方式