遍历Map集合的几种方式
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class Mmmmmap {
public static void main(String[] args){
HashMap<String,String> map = new HashMap<String,String>();
map.put("name", "xzy");
map.put("age", "22");
map.put("add", "nb");
// 方法一、 通过key 获取 value
for (String key : map.keySet()) {
System.out.println("key= "+ key + " and value= " + map.get(key));
....
}
// 方法二、通过迭代器iterator遍历key 和 value
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
....
}
// 方法三、通过map专用的entrySet 去遍历map
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
....
}
// 方法四、只获取values
for (String v : map.values()) {
System.out.println("value= " + v);
....
}
}
}