map 基本概念
Map: 元素是按照键值对形式存储的. 每一对元素由两部分组成. 分别叫键和值
键是唯一的, 值是可以重复的.
所以 Map 集合的底层数据结构是针对键有效, 跟值无关.
map 相关面试题
Map 接口和 Collection 接口的不同?(面试题)
A:Map 集合是双列集合; Map 集合的键是唯一的, 值是可以重复的. 其实我们也可以简单的理解为 Map 集合的键和值是由 Set 和 List 组成; 数据结构针对键有效.
B:Collection 集合是单列集合; Collection 集合的儿子 Set 是唯一的, List 是可以重复的; 数据结构针对元素有效.
Map 集合常用方法
A: 添加功能
V put(K key,V value): 添加, 替换或者修改. 键不同, 添加到集合. 键相同, 值替换.
B: 移除功能
void clear(): 移除所有映射关系
V remove(Object key): 根据键移除键值对元素, 返回的是键对应的值
C: 判断功能
boolean containsKey(Object key): 判断 Map 集合中是否包含指定的键
boolean containsValue(Object value): 判断 Map 集合中是否包含指定的值
boolean isEmpty(): 判断集合是否为空
D: 获取功能
Set<Map.Entry<K,V>> entrySet(): 返回的是键值对对象的 Set 集合.
V get(Object key): 根据键获取值
Set<K> keySet(): 所有的键的集合
Collection<V> values(): 所有值的集合
int size(): 集合的长度
- public class MapDemo {
- public static void main(String[] args) {
- // 创建集合对象
- // 创建元素
- // 添加元素
- // 遍历集合
- // 创建集合对象
- Map<String, String> map = new HashMap<String, String>();
- // 添加元素
- // V put(K key,V value)
- // System.out.println("put:" + map.put("文章", "马伊俐"));
- // System.out.println("put:" + map.put("文章", "姚笛"));
- map.put("文章", "马伊俐");
- map.put("谢霆锋", "张柏芝");
- map.put("田亮", "叶一茜");
- map.put("汪峰", "章子怡");
- // void clear(): 移除所有映射关系
- // map.clear();
- // V remove(Object key): 根据键移除键值对元素, 返回的是键对应的值
- // System.out.println("remove:" + map.remove("汪峰"));
- // System.out.println("remove:" + map.remove("汪峰 2"));
- // boolean containsKey(Object key): 判断 Map 集合中是否包含指定的键
- // System.out.println("containsKey:" + map.containsKey("田亮"));
- // System.out.println("containsKey:" + map.containsKey("森碟"));
- // boolean isEmpty(): 判断集合是否为空
- // System.out.println("isEmpty:" + map.isEmpty());
- // int size(): 集合的长度
- System.out.println("size:" + map.size());
- System.out.println("map:" + map);
- }
- }
map 集合的遍历
1, 通过获取所有的 key 按照 key 来遍历
- //Set<Integer> set = map.keySet(); // 得到所有 key 的集合
- for (Integer in : map.keySet()) {
- String str = map.get(in);// 得到每个 key 多对用 value 的值
- }
2, 通过 Map.entrySet 使用 iterator 遍历 key 和 value
- Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
- while (it.hasNext()) {
- Map.Entry<Integer, String> entry = it.next();
- System.out.println("key=" + entry.getKey() + "and value=" + entry.getValue());
- }
3, 通过 Map.entrySet 遍历 key 和 value, 推荐, 尤其是容量大时
- for (Map.Entry<Integer, String> entry : map.entrySet()) {
- //Map.entry<Integer,String> 映射项 (键 - 值对) 有几个方法: 用上面的名字 entry
- //entry.getKey() ;entry.getValue(); entry.setValue();
- //map.entrySet() 返回此映射中包含的映射关系的 Set 视图.
- System.out.println("key=" + entry.getKey() + "and value=" + entry.getValue());
- }
4, 通过 Map.values() 遍历所有的 value, 但不能遍历 key
- for (String v : map.values()) {
- System.out.println("value=" + v);
- }
来源: http://www.bubuko.com/infodetail-3070369.html