Open In App

Generic MultiMap in java

Last Updated : 09 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, a map is an interface. The map exists in the package java.util. The data is stored as a Key-Value pair in the map, which is a collection of keys and values. HashMap, TreeMap, and LinkedHashMap are the tools used to implement it. Every class has unique characteristics. It does not maintain the key order.

What is MultiMap?

Multiple identical keys with distinct values can be stored with MultiMap. Regretfully, Java does not offer this feature. We will discover how to implement it in Java in this article. Because TreeMap maintains the keys in sorted order and MultiMap saves the keys in sorted order as well, MultiMap can be built in Java using TreeMap. However, MultiMap has the advantage of supporting many identical key-value pairs.

What is Generic MultiMap?

A Generic MultiMap is a data structure that can hold more than one value for a single key, and it’s far designed to paint with any keys and values. Generics will let you create instructions, interfaces, and strategies that function on parameters of various sorts. In the context of the MultiMap elegance, the magnificence may be used to keep and retrieve key-fee pairs of any type.

Methods in Generic MultiMap

  • void put(K Key, V value): To put a new Key-Value pair
  • void get(K key): To get the values mapped with the key.
  • void removeAll(K key): To remove all the values mapped with the given key.
  • boolean remove(K key, V value): To remove specific Key-Value pair.
  • int size(): To get the size of the MultiMap.
  • boolean containsKey(K key): To check the key is present in the MultiMap.
  • String toString(): Method is overridden to print MultiMap.

Note: The time complexity of all of the above operations is O(log n) except size() it is O(1) and toString is O(key*values).

Illustration of Generic MultiMap in Java:

Java




//Java program to demonstrate Generic MultiMap
import java.util.*;
  
class MultiMap<K, V> {
  
    private TreeMap<K, List<V>> treeMap;
    private int size;
  
    public MultiMap() 
    {
        treeMap = new TreeMap<>();
        size = 0;
    }
  
    public void put(K key, V value) 
    {
        treeMap.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
        ++size;
    }
  
    public List<V> get(K key) 
    {
        return this.containsKey(key) ? treeMap.get(key) : new ArrayList<>();
    }
  
    public void removeAll(K key) 
    {
        if (this.containsKey(key)) 
        {
            size -= treeMap.get(key).size();
            treeMap.remove(key);
        }
    }
  
    public boolean remove(K key, V value) 
    {
        boolean isKeyPresent = this.containsKey(key);
        if (!isKeyPresent) 
        {
            return false;
        }
  
        boolean isValuePresent = treeMap.get(key).contains(value);
        if (isValuePresent) 
        {
            treeMap.get(key).remove(value);
            --size;
        }
  
        return isKeyPresent && isValuePresent;
    }
  
    public int size() 
    {
        return this.size;
    }
  
    public boolean containsKey(K key) 
    {
        return treeMap.containsKey(key);
    }
  
    @Override
    public String toString() 
    {
        StringBuilder printMultiMap = new StringBuilder("{\n");
  
        for (K key : treeMap.keySet()) 
        {
            printMultiMap.append(key).append(" = ").append(treeMap.get(key)).append("\n");
        }
  
        printMultiMap.append("}");
  
        return printMultiMap.toString();
    }
}
  
public class Main {
    public static void main(String[] args) 
    {
        // initializing multimap
        MultiMap<Character, Integer> multiMap = new MultiMap<>();
  
        // adding values in multimap
        multiMap.put('A', 1);
        multiMap.put('B', 2);
        multiMap.put('C', 3);
        multiMap.put('A', 4);
        multiMap.put('B', 5);
        multiMap.put('A', 6);
        multiMap.put('D', 7);
        multiMap.put('D', 8);
  
        // Printing Multimap
        System.out.println("The Key and values in the MultiMap are: ");
        System.out.println(multiMap);
  
        // Printing size
        System.out.println("\nSize Of multiMap : " + multiMap.size());
  
        // Remove specific key-value pair
        multiMap.remove('A', 4);
  
        // MultiMap After performing remove operations
        System.out.println("\nAfter performing remove operation");
        System.out.println("The Key and values in the MultiMap are: ");
        System.out.println(multiMap);
        System.out.println("\nSize Of multiMap : " + multiMap.size());
  
        // This will remove all the values associated with the key
        multiMap.removeAll('D');
  
        // MultiMap After performing remove operations
        System.out.println("\nAfter performing removeAll operation");
        System.out.println("The Key and values in the MultiMap are: ");
        System.out.println(multiMap);
        System.out.println("\nSize Of multiMap : " + multiMap.size());
  
        // get values
        System.out.println("Values in the MultiMap associated with the key are: ");
        System.out.println(multiMap.get('B'));
  
        // check key is present or not
        System.out.println("\nIs 'A' Present?" + multiMap.containsKey('A'));
  
        // MultiMap After performing all operations
        System.out.println("\nKey and Values in MultiMap : ");
        System.out.println(multiMap);
    }
}


Output

The Key and values in the MultiMap are: 
{
A = [1, 4, 6]
B = [2, 5]
C = [3]
D = [7, 8]
}
Size Of multiMap : 8
After performing remove operation
The Key and values in the MultiMap are: 
{
A = [1, 6]
B = [2, 5]
C = [3]
D = [7, 8]
}
Size Of multiMap : 7
After performing removeAll operation
The Key and values in the MultiMap are: 
{
A = [1, 6]
B = [2, 5]
C = [3]
}
Size Of multiMap : 5
Values in the MultiMap associated with the key are: 
[2, 5]
Is 'A' Present?true
Key and Values in MultiMap : 
{
A = [1, 6]
B = [2, 5]
C = [3]
}


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads