[英]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 (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 - 看起来好像您已经发现了这一点。
我还根据评论中的建议,用强类型泛型替换了你使用的强制转换。
很明显 - 你需要两个嵌套循环:
for (String key1 : outerMap.keySet()) {
Map innerMap = outerMap.get(key1);
for (String key2: innerMap.keySet()) {
// process here.
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.