-1

在我的代码中,我有一个

Map<String,Map<String,customObject>>

我不确定如何迭代此地图并从中获取值。我在这里要做的是通过将密钥传递给外部 Map 来获取封闭的 Map。当我得到封闭的地图时,我需要对其进行迭代并从中获取键和值。你能告诉我我该怎么做吗,因为我有点卡在这里。任何类似类型的示例或代码都有助于更好地理解它。

感谢 Vikeng21

4

4 回答 4

2

您可以使用两个地图的条目集。像这样的东西:

    Map<String,Map<String,String>> map1 = ...
    Set<Entry<String,Map<String,customObject>>> entrySet1 = map1.entrySet();
    for (Entry<String, Map<String, customObject>> entry1 : entrySet1) {
        Map<String,String> map2 = entry1.getValue();
        Set<Entry<String, customObject>> entrySet2 = map2.entrySet();
        for (Entry<String, customObject> entry2 : entrySet2) {
            System.out.println(entry1.getKey() +" -> "+entry2.getKey()+" -> "+entry2.getValue());
        }
    }
于 2012-09-16T17:38:56.543 回答
1

迭代哈希图条目...

for (Map.Entry<String, Map<String, Object>> ent : hashmap.entrySet())
{
    //ent.getKey();   is the key [String]
    //ent.getValue(); is the value [Map<String, Object>]
}

现在从那里开始工作,基本上是一样的。

于 2012-09-16T17:36:51.993 回答
1

我不知道如何迭代这张地图并从中获取值

您将像使用任何地图一样迭代地图的值 - 请参见下面使用这种结构的示例。

Map<String, CustomObject> innerMap = new HashMap<String, CustomObject> ();
innerMap.put("abc", new CustomObject());

Map<String, Map<String, CustomObject>> externalMap = new HashMap<String, Map<String, CustomObject>> ();

externalMap.put("map1", innerMap);

//iterate over all the maps contained in externalMap 
for (Map<String, CustomObject> inner : externalMap.values()) {
    System.out.println(inner);
}

如果您还需要访问密钥,则可以遍历条目集:

for (Entry<String, Map<String, CustomObject>> e : externalMap.entrySet()) {
   System.out.println(e.getKey()); //map1
   System.out.println(e.getValue()); //innerMap
}
于 2012-09-16T17:37:23.207 回答
0

我想这个例子会给你答案....

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class MapInMap {
    public static void main(String[] args) {
        Map<String, MyObj> innerMap01 = new HashMap<String, MyObj>();
        Map<String, MyObj> innerMap02 = new HashMap<String, MyObj>();
        innerMap01.put("OneOne", new MyObj());
        innerMap02.put("TwoOne", new MyObj());

        Map<String, Map<String, MyObj>> maps = new HashMap<String, Map<String, MyObj>>();

        maps.put("One", innerMap01);
        maps.put("Two", innerMap02);

        for (Entry<String, Map<String, MyObj>> map : maps.entrySet()) {
            for (Entry<String, MyObj> innerObject : map.getValue().entrySet()) {
                // your logic
            }
        }
    }
}

class MyObj {
    int i;
}
于 2012-09-16T17:45:20.893 回答