java map 遍历
转自http://rain-2372.iteye.com/blog/1615615
1 package com.spring.test_B11_aop1; 2 3 import java.util.HashMap; 4 import java.util.Iterator; 5 import java.util.Map; 6 import java.util.Set; 7 8 public class MapTest { 9 10 public static void main(String[] args) { 11 // java中遍历MAP的几种方法 12 // Java代码 13 Map<String, String> map = new HashMap<String, String>(); 14 map.put("username", "qq"); 15 map.put("passWord", "123"); 16 map.put("userID", "1"); 17 map.put("email", "qq@qq.com"); 18 19 // 第一种用for循环 20 // Java代码 21 for (Map.Entry<String, String> entry : map.entrySet()) { 22 System.out.println(entry.getKey() + "--->" + entry.getValue()); 23 } 24 25 // 第二种用迭代 26 // Java代码 27 Set<?> set = map.entrySet(); 28 Iterator<?> i = set.iterator(); 29 while (i.hasNext()) { 30 @SuppressWarnings("unchecked") 31 Map.Entry<String, String> entry1 = (Map.Entry<String, String>) i.next(); 32 System.out.println(entry1.getKey() + "==" + entry1.getValue()); 33 } 34 35 36 // 用keySet()迭代 37 // Java代码 38 Iterator<String> it = map.keySet().iterator(); 39 while (it.hasNext()) { 40 String key; 41 String value; 42 key = it.next().toString(); 43 value = map.get(key); 44 System.out.println(key + "--" + value); 45 } 46 47 // 用entrySet()迭代 48 // Java代码 49 Iterator<?> it2 = map.entrySet().iterator(); 50 System.out.println(map.entrySet().size()); 51 String key; 52 String value; 53 while (it2.hasNext()) { 54 @SuppressWarnings("rawtypes") 55 Map.Entry entry = (Map.Entry) it2.next(); 56 key = entry.getKey().toString(); 57 value = entry.getValue().toString(); 58 System.out.println(key + "====" + value); 59 } 60 } 61 }