zoukankan      html  css  js  c++  java
  • Map 方法记录

    Map 方法记录

    一、Map 是一种键-值对(key-value)集合,用于保存具有映射关系的数据

    用法

    Map<Object,Object> map = new HashMap<>();
    map.put("hello", "hello");
    map.put("world","world");
    map.put("world","world1");  
    //注意,Map的键不能重复,只能存储一个,存储的是map.put("world","world1");  

    获取key,value

    • entrySet() 获取Map中key的集合,返回Set类型(注意:Set 集合中的元素是不可重复的,与Map中的键不可重复一样,因此返回Set集合)
    1. 获取Map中key的集合
    Set set = map.entrySet();
    • values() 获取Map中value数据,返回Collection集合
    2. 获取Map中value的集合
    Collection collet = map.values();

    二、遍历Map的三种方式

    • 1.先获取键的Set集合,然后根据键去取值
    Set set = map.keySet();
    for (Iterator iterator = set.iterator(); iterator.hasNext();){
    //先获取键的Set,然后根据键去取值
        Object key = iterator.next();
        String value = (String)map.get(key);
        System.out.println(key + " =" + value);
    }
    • 2.先获取键的Set集合,通过迭代器获取每个元素,直接获取Map.Entry 类型元素 (注:Map(key,value) 就是Map.Entry类型的)
    HashMap map = new HashMap();
    map.put("a","aa");
    map.put("b","bb");
    map.put("c","cc");
    
    Set set = map.entrySet();
    for (Iterator iterator = set.iterator(); iterator.hasNext();){
    //直接获取Map.Entry 
        Map.Entry obj = (Map.Entry) iterator.next();
        System.out.println(obj.getKey());
        System.out.println(obj.getValue());
    }
    • 3.使用增强的for循环,获取Map.Entry类型元素
    Map<String, String> map = new HashMap<String, String>();
    map.put("Java入门教程", "http://c.biancheng.net/java/");
    map.put("C语言入门教程", "http://c.biancheng.net/c/");
    
    for (Map.Entry<String, String> entry : map.entrySet()) {
        String mapKey = entry.getKey();
        String mapValue = entry.getValue();
        System.out.println(mapKey + ":" + mapValue);
    }
  • 相关阅读:
    mysql删选某列重复值
    apache伪静态
    nginx的伪静态
    如何对数据库进行优化
    ci的优缺点
    memcache状态说明
    sql中扩展插入语法
    若给个 个人收款的二维码,如何测试?
    安装自动化测试工具selenium
    PHP 线上项目 无法操作
  • 原文地址:https://www.cnblogs.com/eathertan/p/12584589.html
Copyright © 2011-2022 走看看