有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:遍历另一个HashMap中的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()并使用,=进行分离。还有其他的迭代方法吗


共 (3) 个答案

  1. # 1 楼答案

        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. # 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(),如果在循环入口集时调用,这将导致ConcurrentModificationException——看起来您已经发现了这一点

    我还按照评论中的建议,将强制类型转换与强类型泛型交换了

  3. # 3 楼答案

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

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