标签:blog span entry keyset map int shm sys try
1 Map<Integer, String> map = new HashMap<Integer, String>(); 2 map.put(1, "123"); 3 map.put(2, "abc"); 4 map.put(3, "ab3"); 5 map.put(4, "ab5"); 6 map.put(4, "ab6"); 7 System.out.println(map.size());
第一种方式:
通过Map.keySet遍历key和value
1 Set<Integer> mp = map.keySet(); 2 3 for (Integer key : set) { String str = mp.get(in); 4 System.out.println(in + " " + str); }
第二种方式:
通过Map.entrySet使用iterator遍历key和value
1 Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator(); 2 while (it.hasNext()) { 3 Map.Entry<Integer, String> entry = it.next(); 4 System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue()); 5 }
第三种方式:
通过Map.entrySet遍历key和value
1 for (Map.Entry<Integer, String> entry : map.entrySet()) { 2 System.out.println("key= " + entry.getKey() + " and value= " 3 + entry.getValue()); 4 }
第四种方式:
过Map.values()遍历所有的value,但不能遍历key
1 for (String v : map.values()) { 2 System.out.println("value= " + v); 3 }
标签:blog span entry keyset map int shm sys try
原文地址:http://www.cnblogs.com/clarke157/p/6410298.html