我有一个 map 中的 map 中的 map 。格式为HashMap<String, Map>
示例数据:
deviceName={commandName={dataKey1=[dataValue1], dataKey2=[dataValue2]}}
其设置方式为deviceName
是key
和commandName
是它的值(value)。为了简单起见,现在只有一个命令,但可能有多个命令。在第二次迭代时commandName
是key
和{dataKey1=[dataValue1], dataKey2=[dataValue2]}
是值。在第三次迭代中dataKey1
是关键并且 dataValue1
是值(它是一个数组列表)。
我可以迭代一个,但我不知道如何做到这一点。
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.
}
}
最佳答案
呼应jtahlborn,抽象是你的 friend
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
}
}
关于java - 如何在 map 中的 map 中迭代 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7774302/