Map:
将键映射到值的对象。
-
一个映射不能包含重复的键;
-
每个键最多只能映射到一个值。
-
实现类: HashMap, TreeMap, Hashtable,
-
从以下版本开始:1.2
-
注意
-
1:当有重复的键的时候,后面的值会将前面的值覆盖
-
2:可以添加null键null值,但是只能添加一对
-
3:值可以重复
-
4:map集合主要是和键有关系,只要找到键,就能根据键找到值
₯ -
Map集合其实就是由Set和List构成的
key是Set集合 不能有重复
Value是List集合 可以有重复集合常用方法
添加 put(k,v)
删除 remove(k)
清空 clear();
修改 ???
查询 get(k) 根据键查找值
长度:size();
判断
containsKey 判断是否包含指定的键
containsValue 判断是否包含指定的值
isEmpty 判断集合是否为空
遍历
public static void main(String[] args) {
//1:创建Map集合
HashMap<String, String> map = new HashMap<>();
//2:给集合添加键值对
map.put("超", "俪");
map.put("明", "颖");
map.put("章", "琍");
map.put("章", "姚");
map.put("强", "蓉");
map.put("哲", "蓉");
map.put(null, null);
map.put(null, null);
System.out.println(map);
//2:删除键值对 根据键删除键值对
map.remove("章");
System.out.println("删除后:"+map);
//3:清空键值对
//map.clear();
//System.out.println(map);
//4:根据键查找值 如果此映射不包含该键的映射关系,则返回 null。
System.out.println(map.get("超1"));
//5:获取键值对的对数
System.out.println(map.size());
//6:判断是否包含指定的键
System.out.println(map.containsKey("超"));
//7:判断是否包含指定的值
System.out.println(map.containsValue("俪"));
//8 isEmpty 判断集合是否为空
System.out.println(map.isEmpty());
//9 返回所有的键的set集合
/*System.out.println("---------------------");
Set<String> set = map.keySet();
for (String s : set) {
System.out.println(s);
}
System.out.println("---------------------");
//10 返回所有的值的Collection集合
Collection<String> coll = map.values();
for (String s : coll) {
System.out.println(s);
}*/
System.out.println("---------------------");
//11 遍历键值对1
//11.1 现获取所有的键
Set<String> set = map.keySet();
//11.2 遍历所有的键
for (String key : set) {
//11.3 遍历一个键,然后在根据键获取值
String value = map.get(key);
System.out.println(key+":"+value);
}
System.out.println("---------------------");
//12 遍历键值对2
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for(Map.Entry<String, String> s:entrySet){
System.out.println(s.getKey()+":"+s.getValue());
}
}