How to automatically fill in a value in Map <String, Collection> on request
I often write code like this:
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 instruction ifabove - how can I get rid of it in standard Java? If you can confirm that there is no standard Java solution, it would be nice if you proposed a non-standard library that satisfies this need.
+3
2 answers
Apache Commons collections have MultiMap :
MultiMap mhm = new MultiHashMap();
mhm.put(key, "A");
mhm.put(key, "B");
mhm.put(key, "C");
Collection coll = (Collection) mhm.get(key);
Guava (usually Google Collections) also has a value that supports generics, and has a tree and hash version:
Multimap<String,String> mhm = new TreeMultimap<String,String>();
// etc.
, Multimap<T, S> Map<T, Collection<S>>, put , .
EDIT: Guava, , , Google Collections .
+2
... multimap- Brendan, / java.util:
public static <K,V> Set<V> getTreeSet(Map<K,Set<V>> map, K key) {
Set<V> set = map.get(key);
if (set == null) {
set = new TreeSet<V>();
map.put(key, set);
}
return set;
}
:
Map < String, Set < String > > map = new TreeMap < String, Set < String > >();
String key;
String element;
/* ... */
MapUtils.getTreeSet(map, key).add(element);
, , .
+1