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

Map集合的遍歷

str put entry nbsp ring bsp style try next

 1 package Collection;
 2 
 3 import java.util.HashMap;
 4 import java.util.Iterator;
 5 import java.util.Map;
 6 import java.util.Set;
 7 
 8 import org.junit.Test;
 9 /**
10  * 
11  * @author Administrator
12  *     遍歷Map集合
13  * Map<key,val>
14  */
15 public class TestMap {
16     //把Map集合轉成Set集合,Set集合有叠代器
17 // 方法一: 18 @Test 19 public void testMap() { 20 Map<String,Integer> map = new HashMap<String,Integer>(); 21 map.put("a",1); 22 map.put("b",2); 23 map.put("c",3); 24 map.put("d",4); 25 26 Set<String> set = map.keySet();
27 Iterator<String> it=set.iterator(); 28 while(it.hasNext()) { 29 Object o=it.next(); 30 System.out.println(o+"..."+map.get(o)); 31 32 /**輸出 33 * a...1 34 * b...2 35 * c...3
36 * d...4 37 */ 38 } 39 } 40 41 // 方法二: 42 @Test 43 public void testEntryset() { 44 Map<String,Integer> map = new HashMap<String,Integer>(); 45 map.put("a",4); 46 map.put("b",3); 47 map.put("c",2); 48 map.put("d",1); 49 Set<Map.Entry<String, Integer>> set=map.entrySet(); 50 Iterator<Map.Entry<String,Integer>> it= set.iterator(); 51 while(it.hasNext()) { 52 Map.Entry<String, Integer> m=it.next(); 53 System.out.println(m.getKey()+"........."+m.getValue()); 54 } 55 /** 56 * 輸出 57 * a.........4 58 b.........3 59 c.........2 60 d.........1 61 * 62 */ 63 } 64 65 }

Map集合的遍歷