Jeremy
Jeremy

Reputation: 5433

Existing Java implementation for a map with a list of values?

A common type of datastructure I might use is a

   Map<String,List<MyObject>> myMap...

The common operation I'd do is to add an object to the list given a matching key. For example,

  myMap.addValueToList("Key", myObject)

Implementing this is not very tricky, but it is a bit ugly (for this example, assume that myObject contains the key):

for (MyObject myObject : myObjects) {
   List<MyObject> newList = newArrayList();
   if (myMap.contains(myObject.key)) {
     newList = myMap.get(myObject.key);
   }
   newList.add(myObject);
   myMap.put(myObject.key, newList);
}

I do this kind of operation more often than I'd like. Last time, I wrote my own class for this functionality, but I wonder if there isn't some kind of implementation available in one of the commonly used libraries such as apache.

Upvotes: 1

Views: 52

Answers (2)

amit
amit

Reputation: 178521

This is called a MultiMap, and there is an existing implementation of it in Apache commons: MultiMap

Upvotes: 3

Juvanis
Juvanis

Reputation: 25950

I think Guava MultiMap will save your time.

http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html

And here is a post explaining its usage with examples:

http://tomjefferys.blogspot.nl/2011/09/multimaps-google-guava.html

Upvotes: 2

Related Questions