特点
- Map用于保存具有映射关系的数据,因此Map集合里保存着两组值,一组值用于保存Map里的Key,例外一组用于保存Map里的Value
- Map中的Key和Value都可以是任何引用类型的数据
- Map中的Key不允许重复,即同一个Map对象的任何两个Key通过equals方法比较返回false
- Key和Value之间存在单向一对一关系,即通过指定Key总能找到唯一的,确定的Value
- Key的值可以使null
主要方法
创建
Map<String,Integer> map = new HashMap<String,Integer>();
添加数据
put(Key,Value);
map.put("a",1);
map.put("b",1);
map.put("c",1);
map.put("d",1);
输出指定Key对应的Value
根据Key删除
System.out.println(map.get("a"));
删除数据
根据Key删除
map.remove("a");
集合的长度
map.size();
是否包含特定的Key
map.containsKey("a");
是否包含特定的Value
map.containsValue(1);
清空集合
map.clear();
遍历Map集合
第一种方式
Set<String> keys = map.keySet();
for (String key: keys) {
System.out.println("Key:"+key+" "+"Value:"+map.get(key));
}
第二种方式
Set<Map.Entry<String, Integer>> entries = map.entrySet();
for(Map.Entry<String,Integer> entry : entries){
System.out.println("Key:"+entry.getKey()+" "+"Value:"+entry.getValue());
}