7. Map集合
7.1 概述
- 定义
interface Map<K, V> K:键的类型 V:值的类型
- 特点
- 键值对映射关系
- 一个键对应一个值
- 键不可重复,值可以
- 元素存取无序
基本使用
public class mapdemo0 {public static void main(String[] args) {Map<String, String> map = new HashMap<String, String>();map.put("itheima01", "qf");map.put("itheima02", "ddm");System.out.println(map);}}
7.2 Map集合基本功能
方法 | 方法名 | 说明 | | —- | —- | | V put(K key,V value) | 添加元素 | | V remove(Object key) | 根据键删除键值对元素 | | void clear() | 移除所有的键值对元素 | | boolean containsKey(Object key) | 判断集合是否包含指定的键 | | boolean containsValue(Object value) | 判断集合是否包含指定的值 | | boolean isEmpty() | 判断集合是否为空 | | int size() | 集合的长度,也就是集合中键值对的个数 |
7.3 Map集合的获取功能
方法 | 方法名 | 说明 | | —- | —- | | V get(Object key) | 根据键获取值 | | Set
keySet() | 获取所有键的集合 | | Collection values() | 获取所有值的集合 | | Set > entrySet() | 获取所有键值对对象的集合 | 案例
public class mapdemo1 {public static void main(String[] args) {Map<String, String> map = new HashMap<>();map.put("张无忌", "照明");map.put("郭靖", "黄蓉");map.put("杨过", "小龙女");System.out.println(map.get("张无忌"));Set<String> keyset = map.keySet();for(String key : keyset) {System.out.println(key);}Collection<String> values = map.values();for(String value : values) {System.out.println(value);}}}
