Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
A Multimap is a map that allows a single key to be mapped to multiple values. Because the JDK does not include an implementation of the Multimap, programmers frequently overlook it in Java. Although Google's Guava library and Apache Commons Collections both implement the Multimap interface, wouldn't it be great to implement our own Multimap Java class that we can customize to our liking?
What is Multimap in Java?
In Java, a Multimap is a data structure that maps keys to multiple values. Unlike traditional Java maps, which map each key to a single value, a Multimap allows one key to be associated with multiple values. This can be useful for situations where you need to represent a one-to-many mapping relationship. While there's no built-in implementation in Java's standard library, third-party libraries like Guava provide implementations of Multimaps.
A different approach to implementing multimap in java is to use Google's Guava library and the Apache Commons Collections libraries. Both provide a Multimap interface implementation. It can store multiple values against a single key. Both the keys and values are stored in the collection and can be used instead of MapK, ListV>> or MapK, SetV>> (standard JDK Collections Framework).
However, using Multimap from Google's Guava library is ineffective for us. Instead, we will create our own multimap in java class that can be customized as needed. In Java, creating a Multimap class is simple.
The Java program below shows how to implement the multimap in java class using Map and collection.
import java.util.*;
class MultiMap<K, V>
{
private Map<K, Collection<V>> mymap = new HashMap<>();
//Adding the specified value
public void put(K mykey, V myvalue)
{
if (mymap.get(mykey) == null) {
mymap.put(mykey, new ArrayList<V>());
}
mymap.get(mykey).add(myvalue);
}
//Associating the specified key with the given value
public void puttingIfAbsent(K key, V value)
{
if (mymap.get(key) == null) {
mymap.putting(key, new ArrayList<>());
}
// if the value is absent, insert it
if (!mymap.get(key).contains(value)) {
mymap.get(key).add(value);
}
}
//Returning the collection of values to which the specified key is mapped
public Collection<V> get(Object key) {
return mymap.get(key);
}
//Returns a set view of the keys contained in this multimap
public Set<K> mykeySet() {
return mymap.mykeySet();
}
//Returning a set view of the mappings contained in this multimap
public Set<Map.Entry<K, Collection<V>>> myentrySet() {
return mymap.myentrySet();
}
//Returning a Collection view.
public Collection<Collection<V>> myvalues() {
return mymap.myvalues();
}
//Returning true if this multimap contains a mapping for the specified key.
public boolean ifcontainsKey(Object key) {
return mymap.ifcontainsKey(key);
}
//Removing the mapping for the specified key from this multimap
public Collection<V> remove(Object key) {
return mymap.remove(key);
}
//Returning the total number of key-value mappings
public int mysize()
{
int size = 0;
for (Collection<V> value: mymap.values()) {
size += value.size();
}
return size;
}
//Returning true if this multimap doesn't contain any key-value mappings.
public boolean itisEmpty() {
return mymap.itisEmpty();
}
//Removing all the mappings
public void clearit() {
mymap.clearit();
}
//Removing the entry for the specified key
public boolean removingit(K mykey, V myvalue)
{
if (mymap.get(mykey) != null) // key exists
return mymap.get(mykey).removingit(myvalue);
return false;
}
//Replacing the entry for the specified key
public boolean replace(K mykey, V myoldValue, V mynewValue)
{
if (mymap.get(mykey) != null)
{
if (mymap.get(mykey).removingit(myoldValue)) {
return mymap.get(mykey).add(mynewValue);
}
}
return false;
}
}
class Main
{
public static void main(String[] args)
{
// creating a multimap from past US presidents list
MultiMap<String, String> mymultimap = new MultiMap();
mymultimap.put("Shruti", "Goel");
mymultimap.put("Shruti", "Kapoor");
mymultimap.put("Vivita", "Sharma");
mymultimap.put("Shivangi", "Goyal");
mymultimap.put("Shivangi", "Khorwal");
System.out.println("Multimap\n");
for (String lastName: mymultimap.keySet()) {
System.out.println(lastName + ": " + mymultimap.get(lastName));
}
}
}
You can also try this code with Online Java Compiler
A collection that maps keys to values (similar to Map), but each key can have multiple values associated with it. The contents of a multimap can be represented as a map from keys to nonempty collections of values.
Replaces all values associated with a specified key with the given values.
size()
Returns the total number of key-value pairs in the Multimap.
Frequently Asked Questions
What is the alternative to multimap in Java?
Alternative to Multimap in Java includes using a Map where the values are collections like List or Set for handling multiple values per key.
When to use multimap Java?
Multimap in Java is useful when a one-to-many mapping relationship between keys and values needs to be represented efficiently.
What is the difference between map and multimap in Java?
Both the map and the multimap in java are containers for key/value pairs that are managed as single components. The primary distinction between the two is that keys in a map must be unique, whereas keys in a multimap in java may be duplicated.
How do I remove a multimap key in Java?
The remove() method in Guava's MultiMap in java removes a single key-value pair from the multimap that matches the specified key-value pair. If the pair is removed, it returns true; otherwise, it returns false if no such pair is found.
How do I get my multimap key?
We can use Multimap's member function equal range to find all values of a key (). It takes as an argument the key and returns a pair of multimap iterators. This returned pair contains a range containing the entries with the given key.
What happens when HashMap duplicates keys?
HashMap stores key-value pairs and prevent duplicate keys. If the key is duplicated, the old value replaces the old key.
Conclusion
In conclusion, we delved into the concept and implementation of Multimap in Java, highlighting both custom approaches and Google's Guava library. Understanding this data structure broadens your toolkit for handling one-to-many mappings efficiently. For further exploration of Java and related technologies, check out Coding Ninjas for courses, resources, and programming challenges. Happy coding!