7. Map集合

7.1 概述

  • 定义

interface Map<K, V> K:键的类型 V:值的类型

  • 特点
    • 键值对映射关系
    • 一个键对应一个值
    • 键不可重复,值可以
    • 元素存取无序
  • 基本使用

    1. public class mapdemo0 {
    2. public static void main(String[] args) {
    3. Map<String, String> map = new HashMap<String, String>();
    4. map.put("itheima01", "qf");
    5. map.put("itheima02", "ddm");
    6. System.out.println(map);
    7. }
    8. }

    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() | 获取所有键值对对象的集合 |

  • 案例

    1. public class mapdemo1 {
    2. public static void main(String[] args) {
    3. Map<String, String> map = new HashMap<>();
    4. map.put("张无忌", "照明");
    5. map.put("郭靖", "黄蓉");
    6. map.put("杨过", "小龙女");
    7. System.out.println(map.get("张无忌"));
    8. Set<String> keyset = map.keySet();
    9. for(String key : keyset) {
    10. System.out.println(key);
    11. }
    12. Collection<String> values = map.values();
    13. for(String value : values) {
    14. System.out.println(value);
    15. }
    16. }
    17. }