java中遍历MAP的几种方法
Java代码
1 Map<String,String> map=new HashMap<String,String>();
2 map.put("username", "qq");
3 map.put("passWord", "123");
4 map.put("userID", "1");
5 map.put("email", "qq@qq.com");
Map<String,String> map=new HashMap<String,String>();
map.put("username", "qq");
map.put("passWord", "123");
map.put("userID", "1");
map.put("email", "qq@qq.com");
第一种用for循环
Java代码
6 for(Map.Entry<String, String> entry:map.entrySet()){
7 System.out.println(entry.getKey()+"--->"+entry.getValue());
8 }
for(Map.Entry<String, String> entry:map.entrySet()){
System.out.println(entry.getKey()+"--->"+entry.getValue());
}
第二种用迭代
Java代码
9 Set set = map.entrySet();
10 Iterator i = set.iterator();
11 while(i.hasNext()){
12 Map.Entry<String, String> entry1=(Map.Entry<String, String>)i.next();
13 System.out.println(entry1.getKey()+"=="+entry1.getValue());
14 }
Set set = map.entrySet();
Iterator i = set.iterator();
while(i.hasNext()){
Map.Entry<String, String> entry1=(Map.Entry<String, String>)i.next();
System.out.println(entry1.getKey()+"=="+entry1.getValue());
}
用keySet()迭代
Java代码
15 Iterator it=map.keySet().iterator();
16 while(it.hasNext()){
17 String key;
18 String value;
19 key=it.next().toString();
20 value=map.get(key);
21 System.out.println(key+"--"+value);
22 }
Iterator it=map.keySet().iterator();
while(it.hasNext()){
String key;
String value;
key=it.next().toString();
value=map.get(key);
System.out.println(key+"--"+value);
}
用entrySet()迭代
Java代码
23 Iterator it=map.entrySet().iterator();
24 System.out.println( map.entrySet().size());
25 String key;
26 String value;
27 while(it.hasNext()){
28 Map.Entry entry = (Map.Entry)it.next();
29 key=entry.getKey().toString();
30 value=entry.getValue().toString();
31 System.out.println(key+"===="+value);
32 }