Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a common Data Structure that represent a Map of Lists in Java

I'm looking for a common data sctructure that has the capabilities of a Map<K, List<V>>

Currently what I do is 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);
     }
     ...
}

Isn't there a more generic solution? Am I reinventing the wheel (or a less important artifact)

like image 651
Eran Medan Avatar asked Dec 18 '22 04:12

Eran Medan


1 Answers

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

Personally, I see nothing wrong with your approach. You're trading off the time it took to write (not that long) and maintain against having another dependency on a 3rd party library like Google. Your approach is defensible.

like image 152
duffymo Avatar answered May 01 '23 12:05

duffymo