I find myself often writing such code:
Map < String, Set < String > > map = new TreeMap < String, Set < String > >();
String key;
String element;
/* ... */
Set < String > value = map.get(key);
if (value == null) {
value = new TreeSet < String >();
map.put(key, value);
}
value.add(element);
I hate the if statement above — how can I get rid of it in standard Java? If you can confirm that there is no standard Java solution, it would then be nice if you could suggest a non-standard library that addresses this need.
Apache Commons Collections has a MultiMap:
Guava (used to be Google Collections) has one too, which supports generics, and has both a tree and hash version:
To clarify,
Multimap<T, S>is basically the same as aMap<T, Collection<S>>, andputautomatically creates the collection if it needs to.EDIT: Updated to link to Guava, since apparently Google Collections is deprecated.