0

I want to have the following data structure to store a word with its multiple IDs (int), but I don't know how to put the key-value pair into the following variable "myWord"

Map<String, Set<Integer>> myWord = new HashMap<String, Set<Integer>>();

myWord.put("word1", how to add the ID to the Set here?)

thanks

7 Answers 7

4
Map<String, Set<Integer>> myWord = new HashMap<String, Set<Integer>>();
Set<Integer> mySet = new HashSet<Integer>();
myWord.put("word1", mySet);
Sign up to request clarification or add additional context in comments.

Comments

3
Set<Integer> mySet = new HashSet<Integer>(); // create a set of IDs
mySet.add(1); // add Id to set
mySet.add(2); // add Id to set
myWord.put("word1", mySet); // finally put set in your map

Comments

1
Set<Integer> set=new HashSet<>();
set.add(id);// Similarly all ids here
myWord.put("word1", set)

Comments

0
Set mySet = new HashSet<Integer>();
mySet.add(3);
Map<String, Set<Integer>> myWord = new HashMap<String, Set<Integer>>();

myWord.put("word1", mySet);

Comments

0

You might also consider using a HashMultimap, which more powerfully represents the data structure you are trying to build.

Multimap<String, Integer> myWord = HashMultimap.create();
myWord.put("word1", 2);

Comments

0
Set<Integer> mySet = new HashSet<Integer>(); // create a set of ids for each word
mySet.add(1); // add Id to the set
mySet.add(2); // add Id to the set
myWord.put("word1", mySet); // for every word put the corresponding set in the map

Comments

0
    Map<Integer, Set<Integer>> adjacent = new HashMap<Integer,Set<Integer>>(n);
    for (int i = 0; i < m; i++) {
        int nodeA = s.nextInt();
        int nodeB = s.nextInt();
        if (!adjacent.containsKey(nodeA)) { **checking if the nodes contains A** 
            adjacent.put(nodeA, new HashSet<Integer>()); **If node A is not present it is being added**
        } 
        adjacent.get(nodeA).add(nodeB); **At the end node B is added to node A's list**
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.