We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,344 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

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

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.

2
Contributors
2
Replies
53 Minutes
Discussion Span
1 Year Ago
Last Updated
3
Views
freedomflyer
Light Poster
27 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

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.

~s.o.s~
Failure as a human
Administrator
12,220 posts since Jun 2006
Reputation Points: 3,307
Solved Threads: 783
Skill Endorsements: 55

Absolute genius. Thanks S.O.S.

freedomflyer
Light Poster
27 posts since Jan 2012
Reputation Points: 10
Solved Threads: 0
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page rendered in 0.0556 seconds using 2.64MB