方法名 说明 返回值类型 put(E key,E value) 添加键值对 E get(E key) 获取指定的键所对应的值,如果不存在指定的键,那么返回null E remove(E key) 删除指定的键所对应的键值对 E size() 返回键值对的个数 int keySet() 返回键的集合(返回的是一个Set集合) Set values() 返回值的集合(返回的是一个Collection集合) Collection entrySet() 返回键值对的集合(返回的是一个Set集合) Set containsKey(E key) 判断是否有指定的键所对应的键值对 boolean(有,返回true;没有,返回false) clear() 清空所有键值对 void isEmpty() 判断是否为空 boolean(集合为空,返回true;集合不为空,返回false)
entrySet()方法得到HashMap中各个键值对映射关系的集合。
然后Map.Entry中包含了getKey()和getValue()方法获取键和值。
getKey() 获取K-V键值对的键 E getValue() 获取K-V键值对的值 E
public class Demo {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("abc", "123");
map.put("efg", "456");
// 使用增强型for遍历循环Map集合
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
System.out.println(entry.getKey() + "->" + entry.getValue());
}
}
}
/**
* 打印结果:
* abc->123
* efg->456
*/