Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Multimap in Java
3.
Multimap in Java Implementation:
4.
Using Google's Guava Library
5.
Java Multimap Interface Methods
6.
Frequently Asked Questions
6.1.
What is the alternative to multimap in Java?
6.2.
When to use multimap Java?
6.3.
What is the difference between map and multimap in Java?
6.4.
How do I remove a multimap key in Java?
6.5.
How do I get my multimap key?
6.6.
What happens when HashMap duplicates keys?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

What is a Multimap in Java?

Author Manshi
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

In this article, we will discuss about the implementation of a multimap in Java and also the Multimap interface of the Guava library.

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?

Also see,  Swap Function in Java

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).

Multimap

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.

Must Read Type Conversion in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Multimap in Java Implementation:

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));
        }
    }
}
Output

Practice by yourself on online java compiler for better understanding.

Using Google's Guava Library

The Multimap<K, V> interface is defined in the Guava library's com.google.common.collect package. It implements the following classes:

ArrayListMultimap, HashMultimap, ImmutableListMultimap, ForwardingListMultimap, ForwardingMultimap, ForwardingSetMultimap, ForwardingSortedSetMultimap, ImmutableMultimap, TreeMultimap, ImmutableSetMultimap, LinkedHashMultimap, LinkedListMultimap.

Syntax:

@GwtCompatible  

public interface Multimap<K, V>  

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.

You can also read about entry set java here.

Must Read Difference between ArrayList and LinkedListDuck Number in Java

Java Multimap Interface Methods

Method 

Description

asMap() Returns a view of this Multimap as a Map, where each key is associated with a collection of its corresponding values.
clear() Removes all key-value pairs from the Multimap.
containsEntry(Object key, Object value) Checks if the Multimap contains the specified key-value pair.
containsKey(Object key) Checks if the Multimap contains the specified key.
containsValue(Object value) Checks if the Multimap contains the specified value.
entries() Returns a collection containing all key-value pairs in the Multimap.
equals(Object obj) Checks if this Multimap is equal to another object.
forEach(BiConsumer<? super K, ? super V> action) Performs the given action for each key-value pair in the Multimap.
get(K key) Returns a collection view of the values associated with the specified key.
hashCode() Returns the hash code value for this Multimap.
isEmpty() Checks if the Multimap contains no key-value pairs.
keys() Returns a collection containing all keys in the Multimap.
keySet() Returns a set view of the distinct keys contained in the Multimap.
put(K key, V value) Associates the specified value with the specified key in the Multimap.
putAll(K key, Iterable<? extends V> values) Associates the specified values with the specified key in the Multimap.
putAll(Multimap<? extends K, ? extends V> multimap) Adds all key-value pairs from another Multimap to this Multimap.
remove(Object key, Object value) Removes a single key-value pair with the specified key and value from the Multimap.
removeAll(Object key) Removes all key-value pairs with the specified key from the Multimap.
replaceValues(K key, Iterable<? extends V> 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 this article, we learned about multimap in Java, how we can implement it, and what is Google’s Guava library.

Want To Learn More About brand-new technologies? We Have A Whole Category, visit Coding Ninjas or explore yourself in the following links:

Also, check out these exciting courses from coding ninjas to expand your knowledge, Coding CourseCode StudioInterview ExperienceGuided PathInterview ProblemsTest SeriesLibrary, and Resources

Happy Coding!

Next article
EnumMap
Live masterclass