将一个Set添加到HashMap

时间:2012-12-06 22:34:05

标签: java hashmap

我需要帮助向hashmap添加一个集合:每次我向集合添加一个值时,它将获得密钥的集合并将新值添加到集合中并将集合放回。

display方法应该只返回已经完成的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();
    }
}

2 个答案:

答案 0 :(得分:4)

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);
}

答案 1 :(得分:0)

您可以使用 Google 的 guava SetMultimap 来实现同义词库:

public class Thesaurus {

    private SetMultimap<String, String> thesaurus = Multimaps.synchronizedSetMultimap(HashMultimap.create());  // word -> Set of its synonyms 
    
    
    public void addSynonym(String word, String synonym) {
        thesaurus.put(word, synonym);
    }
    
    public Set<String> getSynonyms(String word) {
        return thesaurus.get(word);
    }
    
    public void removeSynonym(String word, String synonymToRemove) {
        thesaurus.remove(word, synonymToRemove);
    }
}