1,105,197 Community Members

Best Practices for using a [Map] from [String]->[Set]

Member Avatar
freedomflyer
Light Poster
27 posts since Jan 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I am trying to implement within a class I call State some sort of mapping from a String to a set of States.

So far, I have something like this as the initialization of this concept:

Map<String, HashSet<State>> mapping = new HashMap<String, HashSet<State>>();

However, when I perform something like this:

mapping.put(transitionStringToAdd, transitionStateToAdd);

it obviously does not work because I'm not adding a HashSet to the mapping, just a member that I want to be put into the set. Would you all suggest that I create some sort of wrapper class for the HashSet or something along those lines? I need to be able to stuff distinct states into that HashSet and it's befuddling me.

Member Avatar
~s.o.s~
Failure as a human
10,399 posts since Jun 2006
Reputation Points: 2,496 [?]
Q&As Helped to Solve: 992 [?]
Skill Endorsements: 72 [?]
Administrator
Featured
 
1
 

Two ways of doing this:

1) NULL checks every time you add an element. If the "key" is not associated with any underlying set, create a new HashSet, and place it against the key.

Set<State> states = mapping.get(transitionStringToAdd);
if (states == null) {
  states = new HashSet<State>();
  mapping.put(transitionStringToAdd, states);
}
states.add(transitionStateToAdd);

2) If you can afford adding a library, Google Guava provides a class just for this use case: HashMultiMap. It relieves you of the NULL checks but of course something similar is going under the hood. The new code after using this class will look exactly the same as your code snippet.

Member Avatar
freedomflyer
Light Poster
27 posts since Jan 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Absolute genius. Thanks S.O.S.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: