0

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

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

2 回答 2

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);
}
于 2012-12-06T22:41:49.440 回答
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);
    }
}
于 2021-04-29T08:46:35.637 回答