我希望使用以下数据结构来存储具有多个ID(int)的单词,但我不知道如何将键值对放入以下变量“myWord”
Map<String, Set<Integer>> myWord = new HashMap<String, Set<Integer>>();
myWord.put(“word1”,如何将ID添加到此处的Set?)
谢谢
答案 0 :(得分:4)
Map<String, Set<Integer>> myWord = new HashMap<String, Set<Integer>>();
Set<Integer> mySet = new HashSet<Integer>();
myWord.put("word1", mySet);
答案 1 :(得分: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
答案 2 :(得分:1)
Set<Integer> set=new HashSet<>();
set.add(id);// Similarly all ids here
myWord.put("word1", set)
答案 3 :(得分:0)
Set mySet = new HashSet<Integer>();
mySet.add(3);
Map<String, Set<Integer>> myWord = new HashMap<String, Set<Integer>>();
myWord.put("word1", mySet);
答案 4 :(得分:0)
您也可以考虑使用HashMultimap,它更强大地代表您要构建的数据结构。
Multimap<String, Integer> myWord = HashMultimap.create();
myWord.put("word1", 2);
答案 5 :(得分: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
答案 6 :(得分: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**
}