今天看Think in java 的GUI这一章的时候,里面的TextArea这个例子在遍历Map时用到了Map.Entry 和 Map.entrySet() ,记得只见过Map.KeySet()和values()这两个方法,于是到API中一看,Map.entrySet() 这个方法返回的是一个Set
1.package edu.smc.test;
2.
3.import java.util.HashMap;
4.import java.util.Iterator;
5.import java.util.Map;
6.import java.util.Map.Entry;
7.
8.public class TestEntrySet {
9. public static void main(String[] args) {
10. Map<String,String> map=new HashMap<String,String>();
11. map.put("1", "张三");
12. map.put("2", "李四");
13. map.put("3", "王五");
14.
15. System.out.println("方法一:");
16. Iterator iterator=map.entrySet().iterator();
17. while(iterator.hasNext()){
18. Map.Entry<String, String> entry= (Entry<String, String>) iterator.next();
19. System.out.println("key:"+entry.getKey()+" value"+entry.getValue());
20. }
21.
22. System.out.println("方法二:");
23. for (Map.Entry<String, String> m : map.entrySet()) {
24. System.out.println("key:"+m.getKey()+" value"+m.getValue());
25. }
26. }
27.}
package edu.smc.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class TestEntrySet {
public static void main(String[] args) {
Map<String,String> map=new HashMap<String,String>();
map.put("1", "张三");
map.put("2", "李四");
map.put("3", "王五");
System.out.println("方法一:");
Iterator iterator=map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, String> entry= (Entry<String, String>) iterator.next();
System.out.println("key:"+entry.getKey()+" value"+entry.getValue());
}
System.out.println("方法二:");
for (Map.Entry<String, String> m : map.entrySet()) {
System.out.println("key:"+m.getKey()+" value"+m.getValue());
}
}
}
结果:
[html] view plaincopyprint?
1.方法一:
2.key:3 value王五
3.key:2 value李四
4.key:1 value张三
5.方法二:
6.key:3 value王五
7.key:2 value李四
8.key:1 value张三