简体   繁体   English

如何在Java中读取另一个Map中的Map?

[英]How to read a Map inside another Map, in Java?

I'm new to Java, so sorry if this is pretty obvious, but I can't quite understand how to work with 2 HashMaps inside each other I have my main, where I want to add some words to a Map, and then, I want to read them: 我是Java的新手,很抱歉,如果这很明显,但是我不太明白如何在彼此内部使用2个HashMaps,我有我的主要内容,我想在Map中添加一些单词,然后,我想读它们:

public static void main(String[] args) {
    Dicionario d = new Dicionario();
    d.add("english", "BOOK", "Book");
    d.add("french", "BOOK", "livre");
    d.add("portuguese", "BOOK", "livro");
    d.add("english", "YEAR", "year");
    d.add("french", "YEAR", "an");
    d.add("portuguese", "YEAR", "ano");
    System.out.println(d);
}

This Map, has another Map inside him: 这张地图,里面有另一张地图:

private Map<String, Map<String, String> > dic = new HashMap<>();

Then I add those words: 然后我添加这些词:

protected void add(String s1, String s2, String s3){

    Map<String, String> m = new HashMap<>();

    m.put(s2, s3);
    dic.put(s1, m);

}

And redefine the function toString to read them, but only appears 1 value per key: 并重新定义函数toString以读取它们,但每个键只显示1个值:

@Override
public String toString(){
    String s= "";

    for(Map.Entry<String, Map<String,String>> entry : dic.entrySet())
    {
        s += "\"" + entry.getKey() + "\": ";



        for(Map.Entry<String, String> entry2 : dic.get(entry.getKey()).entrySet())
        {
            s+=entry2.getKey() + "->" + entry2.getValue() + "\t";

        }
        s+="\n";
    }

    return s;
}

Why is that? 这是为什么? I am looking at this like if it was a bidimensional array, but with 2 values (key, value) in each position. 我正在看这个,如果它是一个二维数组,但在每个位置有2个值(键,值)。

How can I do to show all the values that the keys from the first map have? 如何显示第一张地图中的键的所有值?

Thanks, and sorry for such a basic question. 谢谢,抱歉这个基本问题。

You need to modify your add method to following 您需要将add方法修改为以下内容

protected void add(String s1, String s2, String s3) {
    Map<String, String> m = null;
    m = dic.get(s1);
    if (m == null) {
        m = new HashMap<>();
    }
    m.put(s2, s3);
    dic.put(s1, m);
}

The problem is that in your add(String, String, String) method, you are instancing a new HashMap each time so you overwrite the previously instanced HashMap from a previous call. 问题是在你的add(String, String, String)方法中,每次都要实例化一个新的HashMap这样你就可以覆盖先前实例化的HashMap

You should update your method this way: 您应该以这种方式更新您的方法:

protected void add(String s1, String s2, String s3){
    Map<String, String> m = dic.get(s1);

    if (m == null) {
        m = new HashMap<>();
        dic.put(s1, m);
    }

    m.put(s2, s3);
}

To avoid having to manage this by hand yourself, I suggest that you use Guava's Table data structure (more specifically HashBasedTable ). 为避免自己手动管理,我建议您使用Guava的Table数据结构(更具体地说是HashBasedTable )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM