java 集合Map

1. Map集合

特点:将键映射到值的对象,一个映射不能包含重复的键; 每个键可以映射到最多一个值。无序。

Map 与 Collection集合的区别

Map集合存储元素成对出现,双列,Collection是单列的

Map的键是唯一的,Collection 的子体系Set是唯一的

Map集合的数据结构针对键有效,与值无关

Collection的集合的数据结构只针对元素有效

功能概述:

1. 添加功能

V put(K key, V value):添加(修改)功能: 如果该键已经存在,则将值替换,并返回前一个键对应的值,第一次存储,返回Null

2. 删除功能:

void clear():移除所有的键值对元素

V remove(Object key):根据键值对删除元素,并把值返回

3. 判断功能

boolean containsKey(Object key):判断集合是否包含指定的键

boolean containsValue(Object value):判断集合是否包含指定的值

boolean isEmpty():判断集合是否为空

4. 获取功能

Set<Map,Entry<K,V>> entrySet():返回键值对对象

V get(Object key):根据键获取值

set<E> keySet():获取集合中所有键的集合

Collection<V> values():获取集合中所有值的集合

5. 长度功能

int size():返回集合键值对的个数

测试:

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<String, String>();
        System.out.println("put:" + map.put("文章", "马伊利"));
        System.out.println("put:" + map.put("文章", "姚笛")); // 如果该键已经存在,则将值修改,并返回前一个键对应的值
        map.put("wangwang", "xiaojingzi");
        map.put("wangzi", "xiaojunzi");
        map.put("hage", "xiaoha");
        System.out.println("map:" + map);
        System.out.println(map.remove("wangwang")); // 返回键所对应的值:"xiaojingzi"
        System.out.println(map.containsKey("wangzi")); // 存在返回true,不存在返回false
        System.out.println(map.size());
        
        System.out.println(map.get("文章")); // 根据键返回值,不存在返回Null

        Set<String> set = map.keySet();        // 返回集合中所有键的结合
        for (String key : set) {
            System.out.println(key);
        }

        Collection<String> con = map.values();    // 返回集合中所有值的集合
        for (String value : con) {
            System.out.println(value);
        }
        
        for(String key : set) {                    // map集合的遍历方式1
            System.out.println(key + "=" + map.get(key));
        }
        
        Set<Map.Entry<String, String>> set1 = map.entrySet();  // map集合的遍历方式2
        for(Map.Entry<String, String> me : set1) {
            System.out.println(me.getKey() + ":" + me.getValue());
        }
    }

2. HashMap类

特点:键是哈希表的结构,可以保证键的唯一性

猜你喜欢

转载自www.cnblogs.com/feng-ying/p/9419761.html