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

    代码示例

    /**
     * @author liaowenhui
     * @date 2020/6/25 11:15
     */
    public class TestMap {
        public static void main(String[] args) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("1", "C++");
            map.put("2", "Java");
            map.put("3", "Python");
    
            //第一种:普遍使用,二次取值
            System.out.println("通过Map.keySet遍历key和value:");
            for (String key : map.keySet()) {
                System.out.println("key= "+ key + " value= " + map.get(key));
            }
    
            //第二种Iterator
            System.out.println("通过Map.entrySet使用iterator遍历key和value:");
            Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> entry = it.next();
                System.out.println("key= " + entry.getKey() + " value= " + entry.getValue());
            }
    
            //第三种:推荐,尤其是容量大时
            //entrySet 只是遍历了一次就把 key 和 value 都放到了 entry 中,效率更高。
            System.out.println("通过Map.entrySet遍历key和value");
            for (Map.Entry<String, String> entry : map.entrySet()) {
                System.out.println("key= " + entry.getKey() + " value= " + entry.getValue());
            }
    
            //第4种:最优最简洁
            // JDK8的迭代方式
            System.out.println("使用JDK8中的Map.forEach 方法");
            map.forEach((key, value) -> {
                System.out.println("key= " + key + " value= " + value);
            });
    
        }
    }

    运行结果

    阿里开发守则中

    项目实战

  • 相关阅读:
    iOS 里面 NSTimer 防止 循环引用
    [leetcode 34] search for a range
    [leetcode 37]sudoku solver
    [leetcode 36] valid sudoku
    [leetcode 48] rotate image
    [leetcode 35] Search Insert Position
    [leetcode 27]Implement strStr()
    [leetcode 26] Remove Duplicates from Sorted Array
    [leetcode 25]Reverse Nodes in k-Group
    [leetcode 24] Swap Nodes in k-Group
  • 原文地址:https://www.cnblogs.com/liaowenhui/p/13663340.html
Copyright © 2011-2022 走看看