given the following code?
final Map<String, List<E>> map = new HashMap<String, List<E>>();
List<E> list = map.get(mapKey);
if (list == null) {
list = new ArrayList<E>();
map.put(mapKey, list);
}
list.add(value);
If there any way I can avoid the null check? But let the Map automatically create the List for me for my first time insertion?
I remember I once saw a specialized Map which is able to do this. However, I forget where I saw already :(
You are looking for Guava's* MultiMap. You may have previously heard about it when it was called "Google Collections".
This blog post talks a little about the MultiMap.
You could use Multimap
from Guava... that's what I'd do :) (And in particular, an ArrayListMultimap
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With