![](/img/trans.png)
[英]How to stream through a Set<Set<Integer>> and put it into a HashMap as the value?
[英]Java: how to save SET<Integer> as value in HashMap?
我想具有以下數據結構來存儲帶有多個ID(int)的單詞,但是我不知道如何將鍵值對放入以下變量“ myWord”
Map<String, Set<Integer>> myWord = new HashMap<String, Set<Integer>>();
myWord.put(“ word1”,如何在此處將ID添加到Set中?)
謝謝
Map<String, Set<Integer>> myWord = new HashMap<String, Set<Integer>>();
Set<Integer> mySet = new HashSet<Integer>();
myWord.put("word1", mySet);
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
Set<Integer> set=new HashSet<>();
set.add(id);// Similarly all ids here
myWord.put("word1", set)
Set mySet = new HashSet<Integer>();
mySet.add(3);
Map<String, Set<Integer>> myWord = new HashMap<String, Set<Integer>>();
myWord.put("word1", mySet);
您可能還考慮使用HashMultimap ,它可以更強大地表示您要構建的數據結構。
Multimap<String, Integer> myWord = HashMultimap.create();
myWord.put("word1", 2);
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
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**
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.