How to join two nullable sets in Java
dictionary, java, set
Solution
I would use Guava's HashMultimap instead of a `Map<String, Set<String>>`. It has the following advantages:
- shortcut methods to add multiple values for a given key, without caring if a Set already exists for this key of not
- always returns a non-null Set when `get(key)` is called, even if nothing was ever stored for this key.
So your code would become:
Set<String> mergedSet = Sets.union(firstMultimap.get(commonKey),
secondMultimap.get(commonKey));
The set would simply be a view over the two sets, which avoids copying every element. But if you want a copy, then do
Set<String> mergedSet = Sets.newHashSet(Sets.union(firstMultimap.get(commonKey),
secondMultimap.get(commonKey)));
If you don't want to go with an external library, then your code is pretty much OK. I would use `Collections.singletonSet()` for the second fallback set though, to avoid an unnecessary empty set creation. And be careful: your code modified the first set. It doesn't make a copy of it. So in the end, every set of the first map is in fact a merged set.
Problem
I have two maps that have a String as the key, and Set as its value. These two maps can share the same keys. I'm trying to merge the two Set values together if the two maps have the same key. The problem is, the second map might be null, and since not all keys are shared between the two maps, the Sets might also be null. I've come up with a couple options, but they all look pretty messy. Was wondering if anyone had a more efficient/prettier way of doing it. This is what I have so far: `Set<String> mergedSet = (firstMap.containsKey(commonKey)) ? firstMap.get(commonKey) : new HashSet<String>();` `mergedSet.addAll(secondMap != null && secondMap.containsKey(commonKey) ? secondMap.get(commonKey) : new HashSet<String>());`