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.

Recommended Answers

All 2 Replies

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.

Absolute genius. Thanks S.O.S.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.