首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Map中迭代Map中的Map

如何在Map中迭代Map中的Map
EN

Stack Overflow用户
提问于 2011-10-15 06:37:39
回答 2查看 1.6K关注 0票数 0

我有一个地图中的地图地图中的地图。格式为HashMap<String, Map> A示例数据:

代码语言:javascript
复制
deviceName={commandName={dataKey1=[dataValue1], dataKey2=[dataValue2]}}

它的设置方式是deviceNamekeycommandName是它的值。为了简单起见,现在只有一个命令,但可以有多个命令。在第二次迭代中,commandNamekey{dataKey1=[dataValue1], dataKey2=[dataValue2]}是值。在第三次迭代中,dataKey1是键,dataValue1是值(它是一个arrayList)。

我可以遍历一个,但我不确定如何做到这一点。

代码语言:javascript
复制
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.
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-10-15 07:49:00

回声jtahlborn,抽象是你的朋友。

代码语言:javascript
复制
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
  }
}
票数 1
EN

Stack Overflow用户

发布于 2011-10-15 07:35:53

假设你想要维护这个结构,你应该对你的cmd map使用类似这样的东西:

代码语言:javascript
复制
Map<String, Map<String, Map<String,List<String>>>>

但是,我建议将这些地图包装在类中,以使您的工作更轻松,代码更整洁。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7774302

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档