Java: 遍历位于另一个 HashMap 中的 HashMap

Java: Iterate through a HashMap which is inside another HashMap

我想遍历另一个 HashMap

中的 HashMap
Map<String, Map<String, String>> PropertyHolder

我能够如下遍历父 HashMap

Iterator it = PropertyHolder.entrySet().iterator();
while (it.hasNext()) {
  Map.Entry pair = (Map.Entry) it.next();
  System.out.println("pair.getKey() : " + pair.getKey() + " pair.getValue() : " + pair.getValue());
  it.remove(); // avoids a ConcurrentModificationException
}

但无法遍历子项 Map,可以通过转换 pair.getValue().toString() 并使用 ,= 分隔来完成。还有其他迭代方法吗?

很明显 - 您需要两个嵌套循环:

for (String key1 : outerMap.keySet()) {
    Map innerMap = outerMap.get(key1);
    for (String key2: innerMap.keySet()) {
        // process here.
    }
}
    for (Entry<String, Map<String, String>> entry : propertyHolder.entrySet()) {
        Map<String, String> childMap = entry.getValue();

        for (Entry<String, String> entry2 : childMap.entrySet()) {
            String childKey = entry2.getKey();
            String childValue = entry2.getValue();
        }
    }

您可以像处理父地图那样迭代子地图:

Iterator<Map.Entry<String, Map<String, String>>> parent = PropertyHolder.entrySet().iterator();
while (parent.hasNext()) {
    Map.Entry<String, Map<String, String>> parentPair = parent.next();
    System.out.println("parentPair.getKey() :   " + parentPair.getKey() + " parentPair.getValue()  :  " + parentPair.getValue());

    Iterator<Map.Entry<String, String>> child = (parentPair.getValue()).entrySet().iterator();
    while (child.hasNext()) {
        Map.Entry childPair = child.next();
        System.out.println("childPair.getKey() :   " + childPair.getKey() + " childPair.getValue()  :  " + childPair.getValue());

        child.remove(); // avoids a ConcurrentModificationException
    }

}

我假设您想在子地图上调用 .remove(),如果在循环 entrySet 时完成这将导致 ConcurrentModificationException - 看起来您已经发现了这一点。

我还按照评论中的建议用强类型泛型替换了您对强制转换的使用。