0

我希望有以下数据结构来存储一个具有多个 ID (int) 的单词,但我不知道如何将键值对放入以下变量“myWord”

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

myWord.put("word1", 这里如何将ID添加到Set中?)

谢谢

4

7 回答 7

4
Map<String, Set<Integer>> myWord = new HashMap<String, Set<Integer>>();
Set<Integer> mySet = new HashSet<Integer>();
myWord.put("word1", mySet);
于 2013-11-12T04:49:43.577 回答
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
于 2013-11-12T04:50:41.817 回答
1
Set<Integer> set=new HashSet<>();
set.add(id);// Similarly all ids here
myWord.put("word1", set)
于 2013-11-12T04:50:35.753 回答
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
于 2013-11-12T05:09:15.963 回答
0

您也可以考虑使用HashMultimap,它更强大地表示您尝试构建的数据结构。

Multimap<String, Integer> myWord = HashMultimap.create();
myWord.put("word1", 2);
于 2013-11-12T04:54:35.717 回答
0
Set mySet = new HashSet<Integer>();
mySet.add(3);
Map<String, Set<Integer>> myWord = new HashMap<String, Set<Integer>>();

myWord.put("word1", mySet);
于 2013-11-12T04:53:24.940 回答
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**
    }
于 2017-12-29T14:14:47.027 回答