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]
}
Similar Reads
Generic Map In Java
Java Arrays store items in an ordered collection and the values can be accessed using the index(an integer). Whereas HashMap stores as a Key/ Value pair. Using HashMap, we can store the items or values and these values can be accessed by indexes/ keys of any type be it Integer, String, Double, Chara
3 min read
Generics in Java
Generics means parameterized types. The idea is to allow a type (like Integer, String, etc., or user-defined types) to be a parameter to methods, classes, and interfaces. Generics in Java allow us to create classes, interfaces, and methods where the type of the data is specified as a parameter. If w
10 min read
TreeMap get() Method in Java
The java.util.TreeMap.get() method of TreeMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key. Syntax: Tree_Map.get(Object key_element) Parameter: The method takes one parameter key_
2 min read
TreeMap in Java
TreeMap is a part of the Java Collection Framework. It implements the Map and NavigableMap interface and extends the AbstractMap class. It stores key-value pairs in a sorted order based on the natural ordering of keys or a custom Comparator. It uses a Red-Black Tree for efficient operations (add, re
12 min read
TreeMap entrySet() Method in Java
The java.util.TreeMap.entrySet() method in Java is used to create a set out of the same elements contained in the treemap. It basically returns a set view of the treemap or we can create a new set and store the map elements into them. Syntax: tree_map.entrySet() Parameters: The method does not take
2 min read
TreeMap clear() Method in Java
The java.util.TreeMap.clear() method in Java is used to clear and remove all of the elements or mappings from a specified TreeMap. Syntax: Tree_Map.clear() Parameters: The method does not accept any parameters. Return Value: The method does not return any value. Below programs are used to illustrate
2 min read
NavigableMap clear() Method in Java
The clear() method of NavigableMap interface in Java is used to clear and remove all of the elements or mappings from a specified Map. Syntax: NavigableMap.clear() Parameters: The method does not accept any parameters. Return Value: The method does not return any value. Below programs are used to il
2 min read
NavigableMap higherEntry() method in Java
The higherEntry() method of NavigableMap interface in Java is used to return a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key existed. Syntax: Map.Entry< K, V > higherEntry(K key) Where, K is the type of key maintained by th
2 min read
Conversion of Java Map to List
In Java, a Map is a collection that maps keys to values and a list is an ordered collection of objects and the List can contain duplicate values. There are some scenarios where we need to convert a Map into a List. In this article, we will explore how to convert the keys, values, or entries from a M
3 min read
NavigableMap ceilingEntry() method in Java
The cielingEntry() method of NavigableMap interface in Java is used to returns a key-value mapping associated with the least key greater than or equal to the given key, or null if there is no such key exists. Syntax: Map.Entry< K, V > ceilingEntry(K key) Parameters: It accepts a single paramet
2 min read