【问题标题】:Loop through a map containing a String and another map循环遍历包含字符串和另一个地图的地图
【发布时间】:2015-06-15 05:26:18
【问题描述】:

我这样声明我的地图:

Map<Integer, Map<Integer, Integer>> junctions = new HashMap<>();

并用数据填充它:

for (int i = 0; i < N; i++) {
            String[] coordinates = s.nextLine().split(" ");
            junctions.put(i, new HashMap<Integer, Integer>());
            junctions.get(i).put(Integer.parseInt(coordinates[0]), Integer.parseInt(coordinates[1]));
        } 

但我无法将其打印出来,也无法使用其中的内容。

我试过这样:

for (Map<Integer, Map<Integer, Integer>> m : junctions.entrySet()) {
            System.out.println(m.getKey() + "/" + m.getValue());
        }

我也尝试过使用junctions.values() 而不是junctions.entrySet()

我需要做什么?

【问题讨论】:

  • 您的示例代码看起来很像您可以将顶层的 Map 替换为列表,因此 e。 G。 List&lt;Map&lt;Integer, Integer&gt;&gt;。或者更好的是List&lt;Pair&lt;Integer, Integer&gt;&gt;

标签: java dictionary foreach hashmap


【解决方案1】:

应该是

for (Map.Entry<Integer, Map<Integer, Integer>> e : junctions.entrySet()) {
    System.out.println(e.getKey() + "/" + e.getValue());
}

for (Map<Integer, Integer> m : junctions.values()) {
    System.out.println(m);
}

取决于您要打印的内容。

【讨论】:

    猜你喜欢
    • 2014-12-04
    • 2022-07-06
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多