zoukankan      html  css  js  c++  java
  • 遍历HashMap的四种方法

    public static void main(String[] args) {
      Map<String,String> map=new HashMap<String,String>();
            map.put("1", "value1");
            map.put("2", "value2");
            map.put("3", "value3");
            map.put("4", "value4");
            
            //第一种:普通使用,二次取值
            System.out.println("
    通过Map.keySet遍历key和value:");  
            for(String key:map.keySet())
            {
             System.out.println("Key: "+key+" Value: "+map.get(key));
            }
            
            //第二种
            System.out.println("
    通过Map.entrySet使用iterator遍历key和value: ");  
            Iterator map1it=map.entrySet().iterator();
            while(map1it.hasNext())
            {
             Map.Entry<String, String> entry=(Entry<String, String>) map1it.next();
             System.out.println("Key: "+entry.getKey()+" Value: "+entry.getValue());
            }
            
            //第三种:推荐,尤其是容量大时  
            System.out.println("
    通过Map.entrySet遍历key和value");  
            for(Map.Entry<String, String> entry: map.entrySet())
            {
             System.out.println("Key: "+ entry.getKey()+ " Value: "+entry.getValue());
            }
            
            //第四种  
            System.out.println("
    通过Map.values()遍历所有的value,但不能遍历key");  
            for(String v:map.values())
            {
             System.out.println("The value is "+v);
            }
     }
    通过Map.keySet遍历key和value:
    Key: 1 Value: value1
    Key: 2 Value: value2
    Key: 3 Value: value3
    Key: 4 Value: value4
    
    通过Map.entrySet使用iterator遍历key和value: 
    Key: 1 Value: value1
    Key: 2 Value: value2
    Key: 3 Value: value3
    Key: 4 Value: value4
    
    通过Map.entrySet遍历key和value
    Key: 1 Value: value1
    Key: 2 Value: value2
    Key: 3 Value: value3
    Key: 4 Value: value4
    
    通过Map.values()遍历所有的value,但不能遍历key
    The value is value1
    The value is value2
    The value is value3
    The value is value4
  • 相关阅读:
    React——JSX语法【三】
    React——虚拟DOM创建的两种方式【二】
    Nginx——虚拟主机简介
    Linux——Centos8虚拟机添加网卡未显示
    React——React简介和基本使用【一】
    Linux——删除系统python导致yum无法使用
    SonarQube——Docker搭建SonarQube服务
    Linux——配置SSH免密登录
    Jumpserver——如何替换多因子认证
    GitLab——如何快速部署GitLab仓库
  • 原文地址:https://www.cnblogs.com/lev1/p/11454353.html
Copyright © 2011-2022 走看看