我有一个 HashMap,它包含另一个 HashMap。我想遍历第一个 HashMap 并使用其中的键值。然后,当我遍历第一个 HashMap 时,我想启动一个内部循环遍历第二个 HashMap,获取所有值。
到目前为止,我遇到的问题是我不知道如何从迭代器中获取 key 。
HashMap<String, HashMap<Integer, String>> subitems = myHashMap.get("mainitem1");
Collection c = subitems.values();
Iterator itr = c.iterator();
while(itr.hasNext())
{
// Get key somehow? itr.getKey() ???
// contains the sub items
HashMap productitem = (HashMap)itr.next();
}
我从 subitems
得到的数据是这样的:
{Item1{0=sub1, 1=sub2}, Item2{0=sub3, 1=sub4}}
然后,在 while 循环中 productitem
包含“子项目”。但是我找不到从哪里可以获取键值“Item1”和“Item2”。
我怎样才能得到这些?
最佳答案
您无法从 values().iterator()
获取 key .
您需要使用 entrySet().iterator()
.这将返回 Map.Entry<K,V>
您可以调用 getKey()
的对象和 getValue()
.
for (Map.Entry<Integer,Key> entry : subitems.keySet()) {
Integer key = entry.getKey();
String value = entry.getValue();
// do stuff
}
我还想补充一点,拥有深度嵌套的 map 列表 map 通常表明您确实想要编写自定义类来保存数据。 特别是本地图具有要使用的预定义键并且列表中值的解释取决于列表中的位置时!我称此代码为 smell "object denial" .
关于java - 从迭代器中获取键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11645733/