java - 向 HashMap 添加集合

标签 java hashmap

我需要帮助向 HashMap 添加一个集合:每次我向集合添加一个值时,它都会获取键的集合,并将新值添加到集合中,然后将集合放回原处。

显示方法应该只返回已经完成的 HashMap 。

package HashMap;

import java.util.HashMap;
import java.util.Set;

public class Thesaurus {
    HashMap<String, Set<String>> words =new HashMap<String,Set<String>>();

    public void add(String x,String y)
    {
        words.put(x,words.get(x).add(y));
    }
    public void display()
    {
        System.out.println(words);
    }
    public static void main(String[] args) {
        Thesaurus tc = new Thesaurus();
        tc.add("large", "big");
        tc.add("large", "humoungus");
        tc.add("large", "bulky");
        tc.add("large", "broad");
        tc.add("large", "heavy");
        tc.add("smart", "astute");
        tc.add("smart", "clever");
        tc.add("smart", "clever");
        tc.display();
    }
}

最佳答案

public void add(String x,String y) {
    Set<String> set = words.get(x);
    if (set == null) {
        words.put(x, set = new HashSet<String>());
    } 
    set.add(y);
}

关于java - 向 HashMap 添加集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13753843/

相关文章:

java - 如何像谷歌一样在java中实现自定义自动建议

java - 如何将对象数组列表写入和检索到文件?

java - 并发 hashmap 不需要同步的 getters/setters 吗?

java - 如何将一行中的元素解析到不同的哈希表中?

java - 比较 2 个结果集的最佳方法

java - 如何在Microstream中正确使用BinaryHandler来存储 volatile 长整型数组?

java - 在 map 中设置多个值

java - 为什么hashmap split方法需要在loHead.treeify(tab)之前判断if(hiHead!=Null)

java - MultiKeyMap 获取方法

java - graphStream 或 Apache Jena