参考 : Java中如何遍历Map对象的4种方法
import java.lang.Object;
import java.util.*;
public class IteratorHashMap{
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>();
map.put("receiveData","Hello world");
map.put("sendData", "I love China!");
System.out.println(map);//{sendData=I love China!, receiveData=Hello world}
System.out.println("---------高效遍历(不使用泛型) Iterator entrySet----------");
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()){
Map.Entry entry = (Map.Entry)iterator.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println("entrySet--->key : " + key + " value : " + value);
}
System.out.println("---------高效遍历(使用泛型) Iterator<Map.Entry<Object, Object>> entrySet----------");
Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, String> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
System.out.println("---------高效遍历 for-each entrySet ----------");
for (Map.Entry<String,String> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ",Value: " + entry.getValue());
}
System.out.println("---------效率低 Iterator keySet()----------");
Iterator iter = map.keySet().iterator();
while (iter.hasNext()){
Object key = iter.next();
Object value = map.get(key);
System.out.println("keySet--->key : " + key + " value : " +value);
}
System.out.println("---------效率低 for-each keySet()----------");
for (String key : map.keySet()) {
String value = map.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
System.out.println("---------业务中未遇到过的 for-each map.keySet() || map.values()----------");
//开发中未遇到过的
//遍历map中的键
for (String key : map.keySet()) {
System.out.println("Key = " + key);
}
//遍历map中的值
for (String value : map.values()) {
System.out.println("Value = " + value);
}
}
}