<pre name="code" class="java">import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* 遍历Map<String, String>的方法, 输出map里所有的<k, v>
* @author Spary Lee
*
*/
public class MapTest {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("name", "ciara");
map.put("age", "25");
map.put("height", "160cm");
//方法一,使用map.entrySet()
System.out.println("方法一");
output(map);
//方法二,使用map.entrySet()+Iterator
System.out.println("方法二");
output2(map);
//方法三,使用map.keySet()
System.out.println("方法三");
output3(map);
//方法四,使用map.keySet()+Iterator
System.out.println("方法四");
output4(map);
}
static void output(Map<String, String> map){
for(Map.Entry<String, String> entry : map.entrySet()){
System.out.println("<" + entry.getKey() + ", " + entry.getValue() + ">");
}
}
static void output2(Map<String, String> map){
Iterator<Entry<String, String>> itr = map.entrySet().iterator();
while(itr.hasNext()){
Map.Entry<String, String> entry = itr.next();
System.out.println("<" + entry.getKey() + ", " + entry.getValue() + ">");
}
}
static void output3(Map<String, String> map){
for(String s : map.keySet()){
System.out.println("<" + s + ", " + map.get(s) + ">");
}
}
static void output4(Map<String, String> map){
Iterator<String> itr = map.keySet().iterator();
while(itr.hasNext()){
String key = itr.next();
System.out.println("<" + key + ", " + map.get(key) + ">");
}
}
}
运行结果:
方法一
<name, ciara>
<age, 25>
<height, 160cm>
方法二
<name, ciara>
<age, 25>
<height, 160cm>
方法三
<name, ciara>
<age, 25>
<height, 160cm>
方法四
<name, ciara>
<age, 25>
<height, 160cm>