簡體   English   中英

訪問嵌套的Java HashMap鍵值對

[英]Accessing Nested Java HashMap Key Value pairs

好的,我確定有更好的方法可以做到這一點。 我所擁有的是一個嵌套的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;
        }
    }

好吧,你可以這樣做:

Map<String, String> m = eQueues.getValue();
if (!m.isEmpty()) {
    Map.Entry<String, String> e = m.entrySet().iterator().next();
}

不過,這實際上並沒有比您所做的更好。 似乎應該使用Map<String, Map.Entry<String, String>>而不是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>


同樣,艾略特在評論中說的是正確的。 請參見例如如何比較Java中的字符串?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM