java - map 内 map 迭代

标签 java dictionary iteration

我有以下嵌套 Map在我的类(class)中定义:

private Map<String, Map<String, String>> messagesByFactTypeAndCategory;

public void setMessagesByFactTypeAndCategory(Map<String, Map<String, String>> messagesByFactTypeAndCategory) {
    this.messagesByFactTypeAndCategory = messagesByFactTypeAndCategory;
}

public Map<String, Map<String, String>> getMessagesByFactTypeAndCategory() {
    if (messagesByFactTypeAndCategory == null) {
        return Maps.newHashMap();
    }
    return messagesByFactTypeAndCategory;
}

我正在尝试但无法遍历 messagesByFactTypeAndCategory映射并获取其中的数据以在控制台中显示。

下面是我迄今为止尝试过的代码:

Map<String, Map<String, String>> newMap = executionResult.getMessagesByFactTypeAndCategory();
Set set = newMap.entrySet();
    Iterator iterator = set.iterator();
    while(iterator.hasNext()) {
        Map.Entry mentry = (Map.Entry)iterator.next();
        System.out.print("key is: "+ mentry.getKey() + " & Value is: ");
        System.out.println(mentry.getValue());
    }

感谢任何帮助!

最佳答案

如果你只需要遍历两个map的所有条目,可以这样做:

for (Entry<String, Map<String, String>> outerMapEntry : messagesByFactTypeAndCategory.entrySet()) {
        // do something with outerMapEntry
        System.out.println(outerMapEntry.getKey() + " => " + outerMapEntry.getValue());
        for (Entry<String, String> innerMapEntry : outerMapEntry.getValue().entrySet()) {
            // do something with inner map entry
            System.out.println(innerMapEntry.getKey() + " => " + innerMapEntry.getValue());
        }
    }

编辑。一些解释。 每个外部映射条目都是一对 String key 和Map<String, String>值(value)。因此,您可以在每次迭代中同时使用键和值执行某些操作。例如,您可以按原样打印键和值。或者您可以遍历该值(它是 Map )并在内循环中单独打印每个值条目。

我相信如何迭代像Map<String, String>这样的“简单” map 是非常清楚的(参见How to efficiently iterate over each Entry in a Map?),所以遍历内部 map 没有困难。

关于java - map 内 map 迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38574907/

相关文章:

java - 我可以通过 Selenium 获取链接位置吗?

list - 字典的ansible访问列表

python 将 beautifulsoup 输出转换为 dict/json

ios - 在 iOS 中使用 Yelp api

python - 跳过循环中的多次迭代

python - Pandas 迭代更新列值

java - Java 中带有主体的 cURL GET 请求

JavaScript 未在 jsp 中运行

java - 覆盖 TalkBack 公告

Java : Iterating a Set in ibatis