【发布时间】:2012-07-25 08:35:27
【问题描述】:
我有一个 HashMap,其中包含另一个 HashMap。我想遍历第一个 HashMap 并使用其中的 Key 值。然后,当我遍历第一个 HashMap 时,我想启动一个内部循环,遍历第二个 HashMap,获取所有值。
到目前为止,我遇到的问题是我无法弄清楚如何从迭代器中获取密钥。
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”。
我怎样才能得到这些?
【问题讨论】:
-
除了按照下面的答案使用
entrySet()外,您还可以使用keySet()来获取密钥。