zoukankan      html  css  js  c++  java
  • Java之遍历Map

     1 public class mapTest {
     2 
     3     public static void main(String[] args) {
     4         Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
     5         map.put(1, 1);
     6         map.put(2, 2);
     7         map.put(3, 3);
     8         add1(map);
     9         add2(map);
    10         add3(map);
    11         add4(map);
    12     }
    13     
    14     //循环map
    15     public static Map<String,Object> add1(Map<Integer, Integer> map) {
    16         for (Map.Entry<Integer, Integer> entry : map.entrySet()) { 
    17           System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
    18         }
    19         return null;
    20     }
    21     
    22     //key  value 单独取
    23     public static Map<String,Object> add2(Map<Integer, Integer> map) {
    24         for (Integer key : map.keySet()) { 
    25               System.out.println("Key = " + key); 
    26             } 
    27             //遍历map中的值 
    28             for (Integer value : map.values()) { 
    29               System.out.println("Value = " + value); 
    30             }
    31         return null;
    32     }
    33     
    34     //使用Iterator遍历
    35     public static Map<String,Object> add3(Map<Integer, Integer> map) {
    36         Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); 
    37         while (entries.hasNext()) { 
    38           Map.Entry<Integer, Integer> entry = entries.next(); 
    39           System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); 
    40         }
    41         return null;
    42     }
    43 
    44     public static Map<String,Object> add4(Map<Integer, Integer> map) {
    45         for (Integer key : map.keySet()) { 
    46               Integer value = map.get(key); 
    47               System.out.println("Key = " + key + ", Value = " + value);
    48         }
    49         return null;
    50     }
    51 }

    PS:如果仅需要键(keys)或值(values)使用方法二。如果你使用的语言版本低于java 5,或是打算在遍历时删除entries,必须使用方法三。否则使用方法一(键值都要)。

    转自:https://www.cnblogs.com/fqfanqi/p/6187085.html

    往事如烟,余生有我.
  • 相关阅读:
    luogu1196 银河英雄传说 (并查集)
    [BZOJ2243][SDOI2011]染色
    [BZOJ1879] [Sdoi2009]Bill的挑战
    [Noip2003] 侦探推理
    [Noip2005] 篝火晚会
    [JZOJ100047] 【NOIP2017提高A组模拟7.14】基因变异
    [九省联考2018]一双木棋chess
    [Noip2009] 靶形数独
    [Luogu2737] [USACO4.1]麦香牛块Beef McNuggets
    [BZOJ3109] [cqoi2013]新数独
  • 原文地址:https://www.cnblogs.com/assistants/p/10064384.html
Copyright © 2011-2022 走看看