Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to optimize Map of List?

Tags:

java

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 :(

like image 871
Cheok Yan Cheng Avatar asked Dec 16 '22 22:12

Cheok Yan Cheng


2 Answers

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.

like image 183
Etienne Neveu Avatar answered Dec 19 '22 14:12

Etienne Neveu


You could use Multimap from Guava... that's what I'd do :) (And in particular, an ArrayListMultimap.)

like image 44
Jon Skeet Avatar answered Dec 19 '22 13:12

Jon Skeet