• 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

    往事如烟,余生有我.
  • 相关阅读:
    大数据学习——hive数据类型
    大数据学习——关于hive中的各种join
    大数据学习——hive的sql练习
    大数据学习——hive显示命令
    大数据学习——hive数仓DML和DDL操作
    大数据学习——hive基本操作
    大数据学习——hive使用
    大数据学习——hive安装部署
    大数据学习——日志分析
    大数据学习——mapreduce运营商日志增强
  • 原文地址:https://www.cnblogs.com/assistants/p/10064384.html
Copyright © 2020-2023  润新知