Implement a Multimap in Java

In this post, we will see how to implement a Multimap in Java.


 

A Multimap is a map that allows mapping of a single key to multiple values. Since JDK doesn’t provides any implementation of the Multimap, programmers often miss it in Java. Although, Google’s Guava Library and Apache Commons Collections both provides implementation of the Multimap interface, wouldn’t it be great to implement our own Multimap class in Java which we can customize to our style.

 
Well writing a Multimap class is actually very simple in Java. Below is simple custom implementation of Multimap class in Java using a Map and a Collection.

 

Download   Run Code

Output:

—– Printing Multimap using keySet —–

George: [Washington, Bush]
Zachary: [Taylor]
John: [Adams, Tyler, Kennedy]
Grover: [Cleveland, Cleveland]

 
Also See: Google Guava’s Multimap Interface in Java

 
References: HashMap (Java Platform SE 8 )

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz