java双列Map集合讲解

Map集合概述:

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

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

创建Map集合对象:多态的方式,具体的实现类HashMap

基本的功能和常用的方法:

public class MapDemo01 {
    public static void main(String[] args) {
        Map<String,String> map=new HashMap<>();
        map.put("001","李");
        map.put("002","王");
        map.put("003","天");
        //如果出现相同的键,值会被替掉
        map.put("003","丁");

        //remove 移除对应的键和值,返回值
        System.out.println(map.remove("001"));
        //Boolean containsKey(Object key) 判断是否包含指定的键
        System.out.println(map.containsKey("001"));
        //boolean isEmpty();是否为空
        System.out.println(map.isEmpty());
        //int size(); 集合的长度
        System.out.println(map.size());
        System.out.println(map);

    }
}

获取功能:

public class MapDemo01 {
    public static void main(String[] args) {
        Map<String,String> map=new HashMap<>();
        map.put("001","李");
        map.put("002","王");
        map.put("003","天");

        //get() 根据建获取值
        System.out.println(map.get("001"));  //李
        //Set<K> keySet();  获取所有键的集合
        Set<String> keySet=map.keySet();

        //Collection<v> values();获取所有值的集合
        Collection<String> values=map.values();
    }
}

遍历Map集合:

public class MapDemo01 {
    public static void main(String[] args) {
        Map<String,String> map=new HashMap<>();
        map.put("001","李");
        map.put("002","王");
        map.put("003","天");
//增强for遍历
      Set<String> keySet = map.keySet();
        for (String key :keySet){
            String value=map.get(key);
            System.out.println(key+","+value);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44126152/article/details/106538960
今日推荐