集合---Map

Map集合介绍:

1.特点:
  存储数据的结构:键值对;
  键唯一:键不能重复;
  一个键最多对应一个值,可以值为空;

public class MapDemo {
        public static void main(String[] args) {
            HashMap<Integer,String> map = new HashMap();
            map.put(1,"北京");
            map.put(1,"北京");//不会存储进去
            map.put(2,"上海");
            map.put(2,"上海");//不会存储进去
            map.put(3,"广州");
            map.put(4,"深圳");
            map.put(5,"");        //值为空
            System.out.println(map);
        }
    }

 

2.Map集合的继承体系:

  

 

 

3.常用的方法:
    put:增加
    remove:删除,删除参数中键所对应的键值对
    put:修改,键唯一,改变值会覆盖原值
    get:查询,根据键, 获取值
    
    size:获取集合的长度
    containsKey:判断集合中是否包含指定的键
    containsValue:判断集合中是否包含指定的值
    
    keySet:获取集合中所有键,组成一个Set集合;因为键是唯一的,所以使用Set集合;
    values:获取集合中所有值,组成一个Collection集合;
    代码实例:
    public class MapDemo02 {
        public static void main(String[] args) {
            HashMap<String,String> map = new HashMap();
            //增加,put
            map.put("乔峰","降龙十八掌");
            map.put("段誉","凌波微步");
            map.put("虚竹","北冥神功");
            map.put("段正淳","一阳指");
            //System.out.println(map);
            //查询,get
            //System.out.println(map.get("乔峰"));
            //修改
            map.put("段誉","六脉神剑");
            System.out.println(map.get("段誉"));
            //删除
            //map.remove("段正淳");
            //System.out.println(map);


        }
    }
    
4.Map集合的遍历:
    1.方式一:键找值;
    public class MapDemo03 {
        public static void main(String[] args) {
            HashMap<String,String> map = new HashMap();

            map.put("乔峰","降龙十八掌");
            map.put("段誉","凌波微步");
            map.put("虚竹","北冥神功");
            map.put("段正淳","一阳指");
            
            //1.获取集合中所有键,得到键的Set集合
            Set<String> keySet = map.keySet();
            //2.遍历键的集合
            for (String key : keySet) {
                //3.,根据键获取对应的值
                String value = map.get(key);
                System.out.println(key+":"+value);
            }
        }
    }
    方式二:获取键值对集合方式:
    public class MapDemo04 {
        public static void main(String[] args) {
            HashMap<String,String> map = new HashMap();

            map.put("乔峰","降龙十八掌");
            map.put("段誉","凌波微步");
            map.put("虚竹","北冥神功");
            map.put("段正淳","一阳指");
            //1.获取键值对集合entries
            Set<Map.Entry<String, String>> entries = map.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                //获取对应的键和值
                String key = entry.getKey();
                String value = entry.getValue();
                System.out.println(key+":"+value);
            }
        }
    }
    
5.LinkedHashMap:
    特点:
    可以保证键的唯一;
    可以保证怎么存就怎么取;
6.TreeMap:
    特点:
    可以保证键的唯一;
    可以排序, (按照元素本身的自然排序);

 

posted @ 2020-04-15 17:09  moonlighter  阅读(136)  评论(0编辑  收藏  举报