zoukankan      html  css  js  c++  java
  • 遍历Map的方式

    遍历Map的方式

    第一种通过 map1.keySet() 获取key  通过key 找到value;
    第二种通过Map.Entry(String,Integer) 获取,然后使用entry.getKey()获取到键,通过entry.getValue()获取到值;

    第三种只遍历键或者值,通过加强for循环;
    第四种Iterator遍历获取,然后获取到Map.Entry<String, String>,再得到getKey()和getValue();
    推荐第四种,尤其是容量大时。

    实现如下:

    package com.blmlove;
    
    import java.util.*;
    
    public class Test {
    
        public static void main(String[] args) {
            //遍历Map
            Map<String, Integer> map1 = new HashMap<String, Integer>();
            map1.put("jack", 20);
            map1.put("rose", 18);
            map1.put("lucy", 17);
            map1.put("java", 25);
    
            //第一种通过 map1.keySet() 获取key  通过key 找到value
            for (String key : map1.keySet()) {
                Integer value = map1.get(key);
                System.out.println("key : "+key+" value : "+value);
            }
    
            //第二种通过Map.Entry(String,Integer) 获取,然后使用entry.getKey()获取到键,通过entry.getValue()获取到值
            for(Map.Entry<String, Integer> entry : map1.entrySet()){
                System.out.println("键 key :"+entry.getKey()+" 值value :"+entry.getValue());
            }
    
            //第三种只遍历键或者值,通过加强for循环
            for(String s1:map1.keySet()){//遍历map的键
                System.out.println("键key :"+s1);
            }
            for(Integer s2:map1.values()){//遍历map的值
                System.out.println("值value :"+s2);
            }
    
            //第四种Iterator遍历获取,然后获取到Map.Entry<String, String>,再得到getKey()和getValue()
            Iterator<Map.Entry<String, Integer>> it=map1.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry<String, Integer> entry=it.next();
                System.out.println("键key :"+entry.getKey()+" value :"+entry.getValue());
            }
        }
    }

    结果展示:

  • 相关阅读:
    PostgreSQL数据损坏与checksum
    go get命令无响应解决方法
    vscode离线安装插件
    windows搭建Go语言环境
    centos7安装zabbix 5.0
    搭建人生重开模拟器
    博客园增加打赏
    记一次halo报错
    VM operation inconsistent with current state
    nextcloud安装onlyoffice
  • 原文地址:https://www.cnblogs.com/blmlove/p/13022106.html
Copyright © 2011-2022 走看看