Map集合详解
map集合简介:
我们已经学习了list和set集合,,已经能够满足大部分的存储需求了,但是list和set只能存储数据本身,顶多在存储数据的时候采用不同的逻辑结构和物理存储结构来影响后期的运算,但是有时候不能只存储数据,还需要存储数据的描述。
特点:存储的键值对映射关系,根据key可以找到value
如果一个数据库中存储了无数个商品,而且又需要经常使用编号来搜索某个商品,那么这个需求有效的数据结构就是Map
map是一种依照键(key)存储元素的容器,一个键和它对应的值组成map集合里的一个元素。键(key)有点像下标,在list中下标是整数,但是在map中键(key)可以是任意类型的对象
map中没有重复的键(key),但是值可以重复,且每个键(key)都有一个对应的值(value)
常用指令
1、添加: 1、V put(K key, V value) (可以相同的key值,但是添加的value值会覆 盖前面的,返回值是前一个,如果没有就返回null) 2、putAll(Map<? extends K,? extends V> m) 从指定映射中将所有映射关 系复制到此映射中(可选操作)。
2、删除 1、remove() 删除关联对象,指定key对象 2、clear() 清空集合对象
3、获取 1:value get(key); 可以用于判断键是否存在的情况。当指定的键不存在的时候,返 回的是null。
3、判断: 1、boolean isEmpty() 长度为0返回true否则false 2、boolean containsKey(Object key) 判断集合中是否包含指定的key 3、boolean containsValue(Object value) 判断集合中是否包含指定的value
4、长度: Int size()
hashmap,键不可以重复,值可以重复。线程不安全
代码如下
public class Day02 {
public static void main(String[] args) {
//定义一个map的容器对象
HashMap<Integer, String> map1 = new HashMap<>();
HashMap<Integer, String> map2 = new HashMap<>();
//Key Value
//map
map1.put(1,"西红柿");
map1.put(2,"圣女果");
map1.put(3,"小番茄");
map1.put(4,"大土豆");
map1.put(5,"马铃薯");
map2.put(1,"烤玉米");
// System.out.println(map);
String str = map1.get(2);
// get 拿取键key,返回值value
System.out.println(str);
// containskey 有值返回TRUE,没有返回false
System.out.println(map1.containsKey(3));
// containsvalue 同上述
System.out.println(map1.containsValue("西瓜"));
// map.putAll();创建map2,输出map1,例如:map.putAll(map1),
map2.putAll(map1);
String st = map2.get(1);
System.out.println(st);
// replance;传键,传值;第二个:传键,旧值,新值;
// map1.replace(10, "地瓜");
// System.out.println(map1.get(10));
map1.replace(1, "西红柿", "甜瓜");
System.out.println(map1.get(1));
// map1.values();所有值,包装成collection,返回给你。返回collection
// Collection<String> Co = map1.values();
// Iterator<String> it = Co.iterator();
// while (it.hasNext()) {
// System.out.println(it.next());
// }
// map1.keySet();返回键,返回set。因为set不允许加重复的值,键也是这个特性。
// Set<Integer> set = map1.keySet();
// Iterator<Integer> it = set.iterator();
// while (it.hasNext()) {
// System.out.println(it.next());
// }
// 返回set集合,entry是一个接口,很像map
Set<Map.Entry<Integer, String>> set = map1.entrySet();
Iterator<Map.Entry<Integer, String>> it = set.iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> en = it.next();
en.getKey();
System.out.println(en.getKey() + "\t" + en.getValue());
}
// hashmap 允许键为null
// treemap 不允许,会报错
TreeMap<Integer, String> map3 = new TreeMap<Integer,String>();
}
}