package com.mcy;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Name {
public static void main(String[] args) throws Exception {
Map<String, String> map = new HashMap<>();
map.put("name", "马春燕");
map.put("age", "23岁啦");
map.put("微信", "Mcy1032528317");
map.put("QQ", "1032528317");
map.put("爱好", "逛吃逛吃逛吃");
//第一种:通过Map.keySet遍历key和value
for (String key : map.keySet()) {
System.out.println("key= " + key + " ;value= " + map.get(key));
}
System.out.println("------------------------------------------------ ");
//第二种:通过Map.entrySet使用iterator遍历
Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> next = iter.next();
System.out.println("key= " + next.getKey() + " ; value= " + next.getValue());
}
System.out.println("------------------------------------------------ ");
//第三种:通过Map.entrySet遍历
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("key= " + entry.getKey() + " ; value= " + entry.getValue());
}
System.out.println("------------------------------------------------ ");
//第四种:通过Map.values()遍历所有的value,但不能遍历key
for (String str : map.values()) {
System.out.println("value= " + str);
}
}
}
运行结果图片:
结果图
网友评论