Java 杂谈码农的世界

2019-01-03

2019-01-04  本文已影响1人  DreamPath

Map集合

Map集合

1.1Map集合概念
img.png
1.2Map集合的常用子类

HashMap<K,V>

LinkedHashMap<K,V>,是HashMap的一个子类。

注意:K, V泛型类型可以一致,也可以不一致。

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author lx
 * @date 2019/1/3 - 17:25
 * public V put(K key, V value) :  把指定的键与指定的值添加到Map集合中。
 * public V remove(Object key) : 把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的值。
 * public V get(Object key) 根据指定的键,在Map集合中获取对应的值。
 * boolean containsKey(Object key) 判断集合中是否包含指定的键。
 * public Set<K> keySet() : 获取Map集合中所有的键,存储到Set集合中。
 * public Set<Map.Entry<K,V>> entrySet() : 获取到Map集合中所有的键值对对象的集合(Set集合)
 */
public class HashMapDemo {
    public static void main(String[] args) {
        HashMap<String, String> hashMap = new HashMap<>();
        //添加元素
        hashMap.put("冯小刚", "范冰冰");
        hashMap.put("李晨", "范冰冰");
        //如果键相同,值不同时,直接会覆盖前面的Value值。
        hashMap.put("冯小刚", "徐帆");

        hashMap.put("冯绍峰", "赵丽颖");
        hashMap.put("霍建华", "林心如");
        hashMap.put("杨幂", "刘恺威");

        System.out.println(hashMap);
        //{冯绍峰=赵丽颖, 霍建华=林心如, 冯小刚=徐帆, 李晨=范冰冰, 杨幂=刘恺威}
            //通过Key删除元素
            hashMap.remove("杨幂");
        System.out.println(hashMap);
        //{冯绍峰=赵丽颖, 霍建华=林心如, 冯小刚=徐帆, 李晨=范冰冰}

        //获取指定键key的value值
        String s = hashMap.get("霍建华");
        System.out.println(s);//林心如

        //判断集合中是否包含指定键
        System.out.println(hashMap.containsKey("杨幂"));//在这之前已经被删除了,返回false

        //判断集合中是否含有指定value值(一般很少用)
        System.out.println(hashMap.containsValue("范冰冰"));//true

        //获取集合中的所有键,并存储到集合中
        Set<String> set=hashMap.keySet();
        System.out.println(set);//[冯绍峰, 霍建华, 冯小刚, 李晨]

            //获取  键值对  对象的集合
        Set<Map.Entry<String,String>> set1=hashMap.entrySet();
        System.out.println(set1);//[冯绍峰=赵丽颖, 霍建华=林心如, 冯小刚=徐帆, 李晨=范冰冰]

        //遍历获取到的键值对的集合
        for (Map.Entry<String,String> ss:set1) {
            System.out.println(ss);
            /*
            冯绍峰=赵丽颖
            霍建华=林心如
            冯小刚=徐帆
            李晨=范冰冰
             */
        }
    }
}
Entry键值对对象
上一篇下一篇

猜你喜欢

热点阅读