2011-10-14 66 views
0

我在地圖內的地圖內有地圖。格式是HashMap<String, Map>採樣數據:如何在地圖內的地圖內迭代地圖

deviceName={commandName={dataKey1=[dataValue1], dataKey2=[dataValue2]}} 

它的設置是deviceNamekeycommandName是它的價值的方式。爲了簡單起見,現在只有一個,但可能有多個命令。在第二次迭代commandNamekey{dataKey1=[dataValue1], dataKey2=[dataValue2]}是值。在第三次迭代中,​​是關鍵字,dataValue1是值(它是一個arrayList)。

我可以遍歷一個,但我不知道如何做到這一點。

public void analyseVersion(Map cmd) { 

    Iterator deviceIT = cmd.keySet().iterator(); 
    while (deviceIT.hasNext()) { 
     String deviceName = (String) deviceIT.next(); 
     //Map<String, Map> cmd = (Map<String, Map>) cmd.get(deviceName);//This will not work. 
     //At this point I want to iterate through each command and for each command iterate through each data set. 
    } 
} 
+2

你爲什麼不使用泛型的聲明? –

回答

1

爲了呼應jtahlborn,抽象是你的朋友

public class Data 
    private Map<String, Object> attributes 

public class Command 
    private Map<String, Data> data; 

public class Device 
    private Map<String, Command> commands; 

// in main, etc 
for (Entry<String, Command> commandEntry : device.getCommandEntries()) 
{ 
    for (Entry<String, Data> dataEntry : commandEntry.getValue().getDataEntries()) 
    { 
    for (Entry<String, Object> attributeEntry : dataEntry.getValue().getAttributeEntries()) 
     // do something 
    } 
} 
0

假設你要保持這種結構,你應該使用這樣的事情你CMD地圖:

Map<String, Map<String, Map<String,List<String>>>> 
然而

,我建議你在課堂上包裝這些地圖,讓您的生活更輕鬆和你的代碼更清潔。