Map对象的遍历方法

  1. 如果键值都要
for (Map.Entry entry : map.entrySet()) {
	String key = entry.getKey();
	String value = entry.getValue();
	System.out.println("Key = " + key + ", Value = " + value);
}
  1. 如果使用的语言版本低于java 5,或是打算在遍历时删除 条目
//使用泛型:
Iterator> iterator = map.entrySet().iterator();
	while (iterator.hasNext()) {
	Map.Entry entry = iterator.next();
	String key = entry.getKey();
	String value = entry.getValue();
	System.out.println("Key = " + key + ", Value = " + value);
}
//不使用泛型:
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
	Map.Entry entry = (Map.Entry) iterator.next();
	String key = (String)entry.getKey();
	String value = (String)entry.getValue();
	System.out.println("Key = " + key + ", Value = " + value);
}
  1. 如果仅需要键(keys)或值(values)
//遍历map中的键
for (String key : map.keySet()) {
	System.out.println("Key = " + key );
}
//遍历map中的值
for (String value : map.values()) {
	System.out.println("Value = " + value);
}

你可能感兴趣的:(Map对象的遍历方法)