Reputation: 53
I am trying to implement a complicated data structure that looks like
Map<A,Set<B>> map = new HashMap<A,Set<B>>();
but I am not sure how to add content to this data structure. I am trying to do a
map.put(a,b);
but that doesn't help as it expects a set. The requirement I have needs to implement this data structure. Any thoughts?
Upvotes: 1
Views: 529
Reputation: 838156
You first need to get the set and then add to it:
map.get(a).put(b);
You may also need to handle the special case that the set doesn't exist already.
Set<B> set = map.get(a);
if (set == null)
{
set = new HashSet<B>();
map.put(a, set);
}
set.put(b);
Upvotes: 0
Reputation: 80176
If you can afford to add a dependency to your project then Guava has support for this. You need to use SetMultimap.
Upvotes: 1
Reputation: 20875
You need to add
your element within the set contained in the hash map:
if (!map.containsKey(a)) {
map.put(a, new Set<B>());
}
map.get(a).add(b);
Upvotes: 1