VOOZH about

URL: https://www.geeksforgeeks.org/java/generic-multimap-in-java/

⇱ Generic MultiMap in java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generic MultiMap in java

Last Updated : 9 Jan, 2024

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:

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]
}
Comment