【问题标题】:Printing HashMap of HashMaps : Map.Entry or java8打印 HashMap 的 HashMap : Map.Entry 或 java8
【发布时间】:2016-11-09 16:14:59
【问题描述】:

我有一个方法可以返回 hashmap 的 hashmap

HashMap<String, HashMap<String, String>> mapofmaps = abcd(<String>, <Integer>);

我正在尝试使用以下代码打印外部哈希图

for (Entry<String, HashMap<String, String>> entry : mapofmaps.entrySet()) {
            String key = entry.getKey();
            System.out.println(key);

      HashMap<String, String> value = entry.getValue();
            System.out.println(key + "\t" + value);
        }

我想遍历内部地图。那里的入口集变量是什么(代码中的???)。

for (Entry<String, HashMap<String, String>> entry : mapofmaps.entrySet()) {
                String key = entry.getKey();
                System.out.println(key);
    for(Entry<String, HashMap<String, String>> entry : ????.entrySet()){
          HashMap<String, String> value = entry.getValue();
                System.out.println(key + "\t" + value);
            }}

我打印哈希图的逻辑是否正确?还是有更好的方法来做到这一点?

【问题讨论】:

  • "我打印哈希图的逻辑是否正确?"不,不是。当您通过内部哈希图进行迭代时,您显然需要 entry 的另一种类型(因为它包含另一种类型的数据)。

标签: java hashmap entryset


【解决方案1】:

它将是entry.getValue().entrySet() 所以

 for(Entry<String, String> innerEntry : entry.getValue().entrySet()){

那么你可以使用

    String key    = innerEntry.getKey();
    String value  = innerEntry.getValue();

值得一提的是,这也可以使用 java 8 Streams 和 lambda 表达式来完成

    HashMap<String, HashMap<String, String>> mapofmaps = new HashMap<>();

    HashMap<String,String> map1 = new HashMap<>();
    map1.put("map1_key1", "map1_value1");

    HashMap<String,String> map2 = new HashMap<>();
    map2.put("map2_key1", "map2_value1");

    mapofmaps.put("map1", map1);
    mapofmaps.put("map2", map2);

     // To print the keys and values
     mapofmaps.forEach((K,V)->{                 // mapofmaps entries
         V.forEach((X,Y)->{                     // inner Hashmap enteries
             System.out.println(X+" "+Y);       // print key and value of inner Hashmap 
         });
     });

mapofmaps.forEach((K,V) : 这需要一个 lambda 表达式,它接受两个输入,即键(字符串)和值(哈希映射)

V.forEach((X,Y)-&gt;{ : 因为这应用于内部(V:通过之前的 foreach 获取)hashmap,所以 Key 和 Value 都将是字符串

进一步阅读参考:

【讨论】:

    【解决方案2】:

    一个简单的数据示例

    Map<String, Integer> map = new HashMap<>();
    map.put("Apple", 10);
        map.put("Motorolla", 20);
        map.put("RealMe", 30);
        map.put("Oppo", 40);
        map.put("Sony", 50);
        map.put("OnePlus", 60);
    
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + ", Stock : " + entry.getValue());
        }
    

    使用 lambda 表达式

    map.forEach((K,V) -> System.out.println(K + ", Stock : " + V));
    

    【讨论】:

      猜你喜欢
      • 2015-04-13
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 2011-08-20
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多