Java:遍历位于另一个HashMap内部的HashMap

3
我想遍历一个嵌套在另一个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()转换并使用,=分隔来实现。是否有其他遍历方法?


1
为什么不使用泛型,避免强制转换呢?你还在使用Java 4吗? - Mik378
3个回答

8
    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();
        }
    }

2
你可以类似于处理父级元素一样迭代子元素的映射表:
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 - 看起来您已经发现了这一点。

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


0

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

for (String key1 : outerMap.keySet()) {
    Map innerMap = outerMap.get(key1);
    for (String key2: innerMap.keySet()) {
        // process here.
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接