zoukankan      html  css  js  c++  java
  • map迭代的四种方式

     1 package com.hungteshun;
     2  
     3 import java.util.HashMap;
     4 import java.util.Iterator;
     5 import java.util.Map;
     6  
     7 /**
     8  * @author hungteshun
     9  * @description:
    10  * @date 2018/11/12 17:53
    11  */
    12 public class TestMap {
    13     public static void main(String[] args) {
    14         Map<Integer, String> map = new HashMap<>();
    15         map.put(1, "张三");
    16         map.put(2, "李四");
    17         map.put(3, "王五");
    18         map.put(4, "王五");
    19         map.put(4, "王五");
    20         System.out.println("map的大小:" + map.size());
    21  
    22         System.out.println();
    23         System.out.println("方式一:通过Map.keySet遍历key和value:");
    24         for (Integer key : map.keySet()) {
    25             String s = map.get(key);
    26             System.out.println(key + ": " + s);
    27         }
    28         System.out.println();
    29  
    30         System.out.println("方式二:通过Map.entrySet遍历key和value:");
    31         System.out.println("推荐,尤其是容量大时");
    32         for (Map.Entry<Integer, String> entry : map.entrySet()) {
    33             System.out.println(entry.getKey() + ": " + entry.getValue());
    34         }
    35         System.out.println();
    36  
    37         System.out.println("方式三:通过Map.entrySet使用iterator遍历key和value:");
    38         Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
    39         while (iterator.hasNext()) {
    40             Map.Entry<Integer, String> entry = iterator.next();
    41             System.out.println(entry.getKey() + ": " + entry.getValue());
    42         }
    43         System.out.println();
    44  
    45         System.out.println("方式四:通过Map.values()遍历所有的value,但不能遍历key");
    46         for (String value : map.values()) {
    47             System.out.println(value);
    48         }
    49     }
    50 }

    运行结果:

     1 map的大小:4
     2  
     3 方式一:通过Map.keySet遍历key和value:
     4 1: 张三
     5 2: 李四
     6 3: 王五
     7 4: 王五
     8  
     9 方式二:通过Map.entrySet遍历key和value:
    10 推荐,尤其是容量大时
    11 1: 张三
    12 2: 李四
    13 3: 王五
    14 4: 王五
    15  
    16 方式三:通过Map.entrySet使用iterator遍历key和value:
    17 1: 张三
    18 2: 李四
    19 3: 王五
    20 4: 王五
    21  
    22 方式四:通过Map.values()遍历所有的value,但不能遍历key
    23 张三
    24 李四
    25 王五
    26 王五
  • 相关阅读:
    RedHat7安装NetCore环境并发布网站
    【WPF学习】第四十二章 透明
    细说枚举
    js获取ip地址,操作系统,浏览器版本等信息,可兼容
    js实现数据流(日志流,报警信息等)滚动展示,并分页(含实现demo)
    js实现点击copy,可兼容
    js实现htmlToWordDemo
    H5 web 存储之 Webstorage
    已发布的WEB项目,如何挂在服务器或者本机的IIS下
    Nuget打包没有注释显示
  • 原文地址:https://www.cnblogs.com/blogxu/p/Map.html
Copyright © 2011-2022 走看看