Search code examples
javahashmap

Adding a Set to HashMap


I need help adding a set to the hashmap: Each time i add a value to the set it will get the set of the key and add the new value to the set and put the set back.

The display method should just return the hashmap, which is completed already.

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

Solution

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