Is there a way to optimize a list map?

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 I can avoid a null check? But let Map automatically create a list for my first insertion?

I remember that once I saw a specialized card capable of doing this. However, I forgot where I already saw :(

+4
source share
5 answers

You are looking for Guava * MultiMap . You may have already heard about this when it was called "Google Collections."

This blog post talks a bit about MultiMap.

+7
source

You can use Multimap from Guava ... what I would do :) (And, in particular, ArrayListMultimap .)

+4
source

If you could, it could save a nanosecond and probably shouldn't spend a lot of time figuring out. If, however, you are trying to optimize performance and you have so many or such large cards that it causes performance problems, you can consider Javolution . They have a quick map and a quick list, which work much better than the default Java map and list.

+1
source

Apache has an array of MultiValueMap collective collections

0
source

If you have a small number of elements, the array may be faster. The overhead of more complex data types is not needed when you have multiple elements, and a linear search helps the JVM load elements faster.

0
source

All Articles