This post will discuss 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 provide any implementation of the Multimap, programmers often miss it in Java. Although Google’s Guava library and Apache Commons Collections both provide an 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. Following is a simple custom implementation of the 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]

That’s all about Multimap implementation in Java.

 
Also See:

Google Guava’s Multimap class in Java

 
Reference: HashMap (Java Platform SE 8 )