Is there a general data structure representing a list map in Java

I am looking for a general data structure that has Map<K, List<V>> capabilities

I'm currently something like

 public class MapOfLists <K,V>{ private Map<K, List<V>> map = new HashMap<K, List<V>>(); public void addItem(K key, V value){ if(!map.containsKey(key)){ map.put(key, new ArrayList<V>()); } List<V> list = map.get(key); list.add(value); } ... } 

Is there no more general solution? I reinvent the wheel (or less important artifact)

+4
source share
4 answers

Like Google MultiMap .... or Apache Commons DefaultMapBag .

Personally, I see nothing wrong with your approach. You trade from the time it took to write (not so long ago), and support against another dependency on a third-party library such as Google. Your approach is justified.

+7
source

I would go with Google Multimap . I would not use the Apache Commons Collections library because it does not support generics, and the Google Collection library is pretty decent, so I have been using Apache Commons Collections for a while. The thing about all the classes in the Google Collections class, and even the Apache Commons Lang, is that if you look at most of your methods, they will usually be small, and it will save one or two lines during coding for you.

But ultimately, when you do not have a large number of conditional blocks in your code, to check if the object is null before [comparing it] [2] or if the list exists on the map to make a choice (to then add an item or create a list and put it on the card), your code will be more readable and with less noise around.

[2]: http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/ObjectUtils.html#equals(java.lang.Object , java.lang.Object)

+2
source

I tend to use the map in an immutable, single-linked list, usually calling it Cons for historical reasons, where the list ends with a null character. In this case, the code above comes down to:

 public void addItem(K key, V value) { map.put ( key, new Cons<V> ( value, map.get ( key ) ) ); } 

since a minus is created with a zero value, since its tail is valid.

+2
source

In core Java, there is nothing that could do what you are trying to do.

There may be some in third-party libraries, but I always wrote my own class, since it is relatively simple.

+1
source

All Articles