curious123
curious123

Reputation: 53

Manipulating a complicated hashmap

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

Answers (3)

Mark Byers
Mark Byers

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

Aravind Yarram
Aravind Yarram

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

Vivien Barousse
Vivien Barousse

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

Related Questions