访问嵌套的Java HashMap键值对

时间:2017-06-01 22:56:46

标签: java hashmap

好的,我确定有更好的方法可以做到这一点。我所拥有的是一个嵌套的HashMap,它包含从XML文件导入的任意数量的K,V对。但是对于父HashMap中的每个Key,只有1个子K,V对。

我想知道是否有一种“更好”的方式对此进行编码而不是我所拥有的。

HashMap<String, HashMap<String,String>> mQueues = Global.mQueues;
for (Map.Entry<String, HashMap<String, String>> eQueues: mQueues.entrySet()) {
    // There is only 1 K,V for each key iterated above
    // This is where I am wondering if there is a better way to do this.  e.g. directly access the Key and Value of the subordinate HashMap
    for (Map.Entry<String, String> sQueue : eQueues.getValue().entrySet()) {
        strGroup = sQueue.getKey();
        strPattern = sQueue.getValue();
    }
    if (eQueues.getKey() == "Default") {
        strDefGroup = strGroup;
    } else {
        if (strParts[0] == strPattern) {
            msg_grp = strGroup;
            boolPatternMatch = true;
        }
    }

1 个答案:

答案 0 :(得分:0)

嗯,你可以这样做:

Map<String, String> m = eQueues.getValue();
if (!m.isEmpty()) {
    Map.Entry<String, String> e = m.entrySet().iterator().next();
}
但是,这并不比你正在做的更好。似乎不是Map<String, Map<String, String>>而应该有Map<String, Map.Entry<String, String>>,或者只是创建一个小对象来描述单个条目中的任何内容:

public class GroupPattern {
    private String group;
    private String pattern;
    public GroupPattern(String group, String pattern) {
        this.group   = group;
        this.pattern = pattern;
    }
    public String getGroup() {
        return group;
    }
    public String getPattern() {
        return pattern;
    }
    // Optionally setters, if it makes sense.
    public void setGroup(String group) {
        this.group = group;
    }
    public void setPattern(String pattern) {
        this.pattern = pattern;
    }
}

然后你有Map<String, GroupPattern>

此外,Elliott在评论中所说的是对的。参见例如How do I compare strings in Java?