1

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.

1
  • You wrote your own class? I once wrote a single static method for this. Your larger code block would suffice for this, although you should create a new ArrayList() only when the key is not in the map, and you only need the put operation in this case, too. Commented May 20, 2014 at 19:32

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Exactly what I wanted and very simple interface. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.