zoukankan      html  css  js  c++  java
  • Java


     1 package com.guyu.day0421;
     2 
     3 import java.util.HashMap;
     4 import java.util.Iterator;
     5 import java.util.Map;
     6 
     7 /**
     8  * @Author: Fred
     9  * @Date: 2021/4/21 11:20
    10  *      遍历 Map:
    11  *          五种方法分别取出Key 或 Value
    12  */
    13 public class Demo02 {
    14     public static void main(String[] args) {
    15         Map<String,String> map = new HashMap<String, String>();
    16         map.put("1","guyu1");
    17         map.put("2","guyu2");
    18         map.put("3","guyu3");
    19 
    20 
    21         //1、普遍使用,二次取值
    22         System.out.println("1.通过map.keySet遍历key和Value:");
    23         for (String key : map.keySet()) {
    24             System.out.println("key=" + key + "  and  value=" + map.get(key));
    25         }
    26 
    27         System.out.println("----------------------1");
    28 
    29         //2、不推荐
    30         System.out.println("2.通过Map.entrySet使用iterator遍历key和value:");
    31         Iterator<Map.Entry<String,String>> it = map.entrySet().iterator();
    32         while (it.hasNext()) {
    33             Map.Entry<String, String> entry = it.next();
    34             System.out.println("key=" + entry.getKey() + "  and  value=" + entry.getValue());
    35         }
    36 
    37         System.out.println("----------------------2");
    38 
    39         //第三种:推荐,尤其是容量大时
    40         System.out.println("3.通过Map.entrySet使用iterator遍历key和value:");
    41         for (Map.Entry<String, String> entry : map.entrySet()) {
    42             System.out.println("key=" + entry.getKey() + " and  value=" + entry.getValue());
    43         }
    44 
    45         System.out.println("----------------------3");
    46 
    47         //第四种
    48         System.out.println("4.通过Map.keyset()遍历所有的key,但不能遍历value");
    49         for (String k : map.keySet()) {
    50             System.out.println("key=" + k);
    51         }
    52 
    53         System.out.println("----------------------4");
    54 
    55         //第四种
    56         System.out.println("5.通过Map.values()遍历所有的value,但不能遍历key");
    57         for (String v : map.values()) {
    58             System.out.println("value=" + v);
    59         }
    60 
    61         System.out.println("----------------------5");
    62 
    63     }
    64 }

    Note:
    欢迎点赞,留言,转载请在文章页面明显位置给出原文链接
    知者,感谢您在茫茫人海中阅读了我的文章
    没有个性 哪来的签名!
    详情请关注点我
    持续更新中

    扫一扫  有惊喜

    © 2021 04 - Guyu.com | 【版权所有 侵权必究】

    没有个性 哪来的签名!
  • 相关阅读:
    从内存池到连接池 老码农眼中的资源池
    资源池(从内存池到连接池)
    资源池设计模式 (Resource Pool)和数据池的简单实现
    数据库连接池的工作原理
    原理 : 线程池、连接池、内存池
    聚簇索引与非聚簇索引(也叫二级索引)
    MyISAM 和 InnoDB 索引的区别
    MySQL 聚簇索引&&二级索引&&辅助索引
    关于如何提高Web服务端并发效率的异步编程技术
    为什么做java的web开发我们会使用struts2,springMVC和spring这样的框架?
  • 原文地址:https://www.cnblogs.com/guyu-/p/14685165.html
Copyright © 2011-2022 走看看