Map集合将键映射到值得对象,一个映射不能包含重复的键,每个键最多映射一个值。
Map与Collection区别:
1.Map是双列集合,Collection是单列集合
2.Map的每个元素由键值对组成,是成对出现的,Collection元素是孤立的
3.Map的key和value的数据类型可以不同
1.HashMap
基于哈希表的Map接口实现,键值允许为null。无序。不同步多线程。
2.LinkedHashMap
是HashMap的子类。基于哈希表+链表。有序,保证迭代顺序。
3.HashTable
此类实现一个哈希表,将键映射到值,键值不允许为null。同步单线程。
增删改查
public V put(K key, V value): 把指定的键与指定的值添加到Map集合中。键不重复返回null,重复返回新的value值。
public V remove(Object key): 把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的值。
public V get(Object key): 根据指定的键,在Map集合中获取对应的值。
boolean containsKey(Object key): 判断集合中是否包含指定的键。
public Set keySet(): 获取Map集合中所有的键,存储到Set集合中。
public Set: 获取到Map集合中所有的键值对对象的集合(Set集合)。
示例:
public void testHashMap() {
Map<String, String> map = new HashMap<>(4);
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
map.put("4", "d");
System.out.println("----- map.keySet()-----");
//获取所有的 key,根据 key 取出对应的value
for (String key : map.keySet()) {
System.out.println("key:" + key + ",value:" + map.get(key));
}
System.out.println("-----获取map种所有的value:map.values()------");
//遍历所有的value
for (String value : map.values()) {
System.out.println("value:" + value);
}
System.out.println("-----获取键值对:map.entrySet()-----");
//取出对应的 key,value 键值对,容量大时推荐使用
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("键值对:" + entry);
//获取 键值对的 key
System.out.println("key:" + entry.getKey());
//获取 键值对的 value
System.out.println("value:" + entry.getValue());
}
System.out.println("----- 通过 Map.entrySet使用iterator遍历 key 和 value -----");
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
}
System.out.println("----- map.forEach JDK1.8 新特性 -----");
map.forEach((key, value) -> {
System.out.println("key=" + key + ",value=" + value);
});
}
注意:存储自定义属性时,必须实现hashCode和equals方法。