目录
1、Map的作用:
由于List查找指定元素的速率较慢,每次都需要从头查找,所以我们使用Map集合,通过<Key,value>的结构进行查找指定元素。
比如坐车通过身份证检验,通过学号查找学生......
2、Map的实现类:
map的实现类有很多,最常用的是HashMap,TreeMap,LinkedHashMap等
i、HashMap:HashMap使用哈希表来实现键值对的存储,具有快速的访问速度。允许使用null作为键或者作为值,但在插入和获取时需要进行特殊处理。
ii、TreeMap:TreeMap基于红黑树实现,可以自动保证键的有序性,但是没有HashMap那么快的访问速度,当遍历排好序的键值对时,TreeMap更有优势。
iii、LinkedHashMap:LinkedHashMap继承自HashMap,但是它通过一个双向链表保证了存储顺序。所以它既有HashMap的快速访问速度,又有按照插入顺序或者访问顺序进行遍历的能力。
3、Map常用方法
Map<String, Integer> map = new HashMap<>();//创建map对象
map.put("apple", 10);//向map中添加指定数据
map.put("banana", 20);//向map中添加指定数据
boolean hasKey = map.containsKey("apple");//判断此map集合里是否存在指定键
boolean hasValue = map.containsValue(20);//判断此map集合里是否存在指定值
int value = map.get("apple");//获取指定键的值
Set<String> keys = map.keySet();//获取所有的键
Collection<Integer> values = map.values();//获取所有的值
map.remove("banana");//根据指定的键删除该键值对
注意:当重复使用put()方法存放同一个key时(比如map.put("apple", 10)之后又写map.put("apple", 30)),由于一个key对应一个value,所以key对应的是最新放进去的值(也就是30),前面放的值会被覆盖。
4、循环方式
下面列举4种遍历方式,
使用for-each循环遍历:
使用for-each循环遍历Map中的所有键值对:
Map<String, Integer> map = new HashMap<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
}
使用Iterator遍历:
使用Iterator遍历Map中的所有键值对:
Map<String, Integer> map = new HashMap<>();
Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, Integer> entry = it.next();
String key = entry.getKey();
Integer value = entry.getValue();
}
遍历所有键:
使用keySet()方法获取所有键,然后遍历所有键:
Map<String, Integer> map = new HashMap<>();
for (String key : map.keySet()) {
Integer value = map.get(key);
}