【Java集合专项】-Map集合(3)

一、概述

 

二、Map

  (1)Map接口的特点

(1) 用于存储任意键值对,(Key-Value)

  (2)   键:无序、无下标、不允许重复(唯一)

(3)值:无序、无下标、允许重复

 

 (2)Map常用方法

(a)创建Map

Map map = new HashMap();

  (b) 添加元素

        //添加元素
        map.put("cn","中国");
        map.put("uk","美国");

(c)遍历

第一种方式,使用KeySet,就能获取到所有的Key值了。

        System.out.println("========keySet()======");
        Set<String> keySet = map.keySet();
        for (String str: keySet
             ) {
            System.out.println(str+"----------"+map.get(str));
        }

第二种方式,使用map.entryset()

        System.out.println("---------entrySet()----------");
        Set<Map.Entry<String,String>> entries = map.entrySet();
        for (Map.Entry<String,String> entry: entries
             ) {
            System.out.println(entry.getKey()+"------------------"+entry.getValue());
        }

entry的效果更好

(d)判断

        System.out.println(map.containsKey("cn"));
        System.out.println(map.containsValue("中国"));

猜你喜欢

转载自blog.csdn.net/MyxZxd/article/details/110351228