zoukankan      html  css  js  c++  java
  • 遍历Map的4种方法(来自网络)

    一、遍历Map的4种方法
    在java中所有的map都实现了Map接口,因此所有的Map(如HashMap, TreeMap, LinkedHashMap, Hashtable等)都可以用以下的方式去遍历。
    • 在for循环中使用entries实现Map的遍历: 
    public static void main(String[] args) {
        Map <String,String>map = new HashMap<>();
        map.put("熊大", "棕色");
        map.put("熊二", "黄色");
     
        for(Map.Entry<String, String> entry : map.entrySet()){
            String mapKey = entry.getKey();
            String mapValue = entry.getValue();
            System.out.println(mapKey+":"+mapValue);
        }
    }
    • 在for循环中遍历key或者values,一般适用于只需要map中的key或者value时使用,在性能上比使用entrySet较好;
    public static void main(String[] args) {
        Map <String,String>map = new HashMap<>();
        map.put("熊大", "棕色");
        map.put("熊二", "黄色");
     
        for(String key : map.keySet()){
            System.out.println(key); //熊大
        }
     
        for(String value : map.values()){
            System.out.println(value); //棕色
        }
    }
    • 通过Iterator遍历;
    public static void main(String[] args) {
        Map <String,String>map = new HashMap<>();
        map.put("熊大", "棕色");
        map.put("熊二", "黄色");
     
        Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
        while(entries.hasNext()){
            Map.Entry<String, String> entry = entries.next();
            System.out.println(entry.getKey() + ":" + entry.getValue()); //熊大:棕色
        }
    }
    • 通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作;
    public static void main(String[] args) {
        Map <String,String>map = new HashMap<>();
        map.put("熊大", "棕色");
        map.put("熊二", "黄色");
     
        for(String key : map.keySet()){
            System.out.println(key + "-->" +map.get(key)); //熊大-->棕色
        }
    }
     
  • 相关阅读:
    leetcode38.外观数列(循环匹配)
    leetcode35.搜索插入位置(遍历并进行大小判断)
    leetcode28.实现strStr()(暴力拆解,双指针,KMP算法)
    JavaScript对象
    数组迭代
    数组的用法:
    数组
    while与do while 区别 for循环的简介及break和continue的区别
    for循环语句
    if.......else语句子
  • 原文地址:https://www.cnblogs.com/duomen/p/13245068.html
Copyright © 2011-2022 走看看