• map遍历的几种方式


    1、通过map.entrySet( )遍历:

    Map<String, String> map = new HashMap<String, String>();
    for (int i = 0; i < 4; i++) {
    String s = "数字" + i;
    map.put("zhi-" + i, s);
    }
    Set<Entry<String, String>> s = map.entrySet();
    int size = s.size();
    for(Map.Entry<String,String> entry:map.entrySet()) {
    String value =entry.getValue();
    String key = entry.getKey();
    System.out.println("key:"+key+",value:"+value);
    }

    输出结果为:

    key:zhi-0,value:数字0
    key:zhi-1,value:数字1
    key:zhi-2,value:数字2
    key:zhi-3,value:数字3

    2、通过map.keySet()及map.value()遍历:

    Map<String, String> map = new HashMap<String, String>();
    for (int i = 0; i < 4; i++) {
    String s = "数字" + i;
    map.put("zhi-" + i, s);
    }

    for (String key : map.keySet()) {
    System.out.println(key);
    }
    for(String value:map.values()) {
    System.out.println(value);
    }

    输出结果为:

    zhi-0
    zhi-1
    zhi-2
    zhi-3
    数字0
    数字1
    数字2
    数字3

    3、使用 Iterator遍历:

    Map<String, String> map = new HashMap<String, String>();
    for (int i = 0; i < 4; i++) {
    String s = "数字" + i;
    map.put("zhi-" + i, s);
    }

    Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
    while (entries.hasNext()) {
    Map.Entry<String, String> data = entries.next();
    System.out.println("key:" + data.getKey() + ",value:" + data.getValue());
    }

    输出结果为:

    key:zhi-0,value:数字0
    key:zhi-1,value:数字1
    key:zhi-2,value:数字2
    key:zhi-3,value:数字3

    4、通过map.get(key)遍历:

    Map<String, String> map = new HashMap<String, String>();
    for (int i = 0; i < 4; i++) {
    String s = "数字" + i;
    map.put("zhi-" + i, s);
    }

    for(String key:map.keySet()) {
    String value = map.get(key);
    System.out.println(key+" "+value);
    }

    输出结果为:

    zhi-0 数字0
    zhi-1 数字1
    zhi-2 数字2
    zhi-3 数字3

  • 相关阅读:
    MySQL之数据的备份与还原
    调用、查看、修改、删除存储过程和函数
    变量的使用、游标的使用、流程控制的使用
    存储过程与函数
    elementUI 表格设置表头样式
    oracle先排序再分页
    postgresql行转列
    crosstab(unknown, unknown) does not exist
    sublime安装php_beautifier来格式化PHP代码
    从今天开始我要经常更新博客
  • 原文地址:https://www.cnblogs.com/qqzhulu/p/10367117.html
Copyright © 2020-2023  润新知