How to Implement MultiMap in Java Using TreeMap?
Last Updated :
17 Feb, 2023
Map is an interface in java. Present in java.util package. The map is the collection of keys and values and it stores the data as a Key-Value pair. It is implemented by HashMap, TreeMap, and LinkedHashMap. Each class has its own features. It doesn't keep the order of keys.
What is TreeMap in java?
TreeMap is used to implement the Map interface in java. It is also stored as a Kay-Value pair but this gives an extra feature that is sorting. It keeps all keys in a sorted manner. It takes O(log n) time to insert a key in the TreeMap.
What is MultiMap?
MultiMap is used to keep multiple same keys with different values. Unfortunately, java does not provide this functionality. In this article, we will learn How we can implement it in java. The C++ language supports it.
MultiMap can be implemented in java using TreeMap because it keeps the keys in sorted order and multimap also stores the keys in sorted order, but the advantage of the multimap is to support multiple same key-value pairs.
We implemented the below methods in MultiMap:
void put(char Key, int value); // To put a new Key-Value pair
void get(char key); // To get the values mapped with key
void removeAll(char key); // To remove all values mapped with given key
boolean remove(char key, int value); // To remove specific Key-Value pair
int size(); // To get Size of MultiMap
boolean containsKey(char key); // To check key is present in MultiMap
String toString(); // This method is override to print the multimap
The Time Complexity of all above operations is O(log n) except size() it's O(1) and toString is O(key*values).
Below is the implementation of MultiMap in Java using TreeMap
Java
/*package whatever //do not write package name here */
import java.util.*;
// MultiMap Implementation
class MultiMap {
// Key is a Type of Character
// Value is a Type of Integer
private TreeMap<Character, List<Integer> > treeMap;
private int size;
// Constructor
public MultiMap()
{
treeMap = new TreeMap<Character, List<Integer> >();
size = 0;
}
// to Add key-value
public void put(char key, int value)
{
treeMap.computeIfAbsent(key, k -> new ArrayList<>())
.add(value);
++size;
}
// get function -> returns a values mapped with key
public List<Integer> get(char key)
{
return this.containsKey(key)
? treeMap.get(key)
: new ArrayList<Integer>();
}
// this will remove key and all values associated with
// it
public void removeAll(char key)
{
if (this.containsKey(key)) {
size -= treeMap.get(key).size();
treeMap.remove(key);
}
}
// this will remove a specific pair of key and value if
// value is mapped with same key a
// and return true if same key and value removed from
// MultiMap else false.
public boolean remove(char key, int value)
{
boolean isKeyPresent = this.containsKey(key);
// If key not present then return false;
if (!isKeyPresent) {
return false;
}
boolean isValuePresent
= treeMap.get(key).contains(value);
if (isValuePresent) {
treeMap.get(key).remove(new Integer(value));
--size;
}
return isKeyPresent && isValuePresent;
}
// this function will return the size of MultiMap
public int size() { return this.size; }
// To check key is present or not
public boolean containsKey(char key)
{
return treeMap.containsKey(key);
}
// Override toString method to print MultiMap with key
// and value rather in object form
@Override public String toString()
{
String printMultiMap = "{\n";
for (char key : treeMap.keySet()) {
printMultiMap += key + " = "
+ treeMap.get(key).toString()
+ "\n";
}
printMultiMap += "}";
return printMultiMap;
}
}
public class GFG {
public static void main(String[] args)
{
// initializing multimap
MultiMap 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("Key and Values in MultiMap : ");
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("Key and Values in MultiMap : ");
System.out.println(multiMap);
System.out.println("\nSize Of multiMap : "
+ multiMap.size());
// Remove all value associated with key
multiMap.removeAll('D');
// MultiMap After performing remove operations
System.out.println(
"\nAfter performing removeAll operation");
System.out.println("Key and Values in MultiMap : ");
System.out.println(multiMap);
System.out.println("\nSize Of multiMap : "
+ multiMap.size());
// get values
System.out.println(
"Values in MultiMap associated with key: ");
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);
}
}
OutputKey and Values in MultiMap :
{
A = [1, 4, 6]
B = [2, 5]
C = [3]
D = [7, 8]
}
Size Of multiMap : 8
After performing remove operation
Key and Values in MultiMap :
{
A = [1, 6]
B = [2, 5]
C = [3]
D = [7, 8]
}
Size Of multiMap : 7
After performing removeAll operation
Key and Values in MultiMap :
{
A = [1, 6]
B = [2, 5]
C = [3]
}
Size Of multiMap : 5
Values in MultiMap associated with key:
[2, 5]
Is 'A' Present?true
Key and Values in MultiMap :
{
A = [1, 6]
B = [2, 5]
C = [3]
}
Similar Reads
TreeMap clone() Method in Java with Examples
In Java, clone() method of the TreeMap class is used to return a shallow copy of the mentioned treemap. It just creates a copy of the map. --> java.util Package --> TreeMap Class --> clone() Method Syntax: Tree_Map.clone() Parameters: The method does not take any parameters. Return Type: A
2 min read
Java Program to Implement B+ Tree
The B+ tree is a self-balancing tree data structure commonly used in database and file systems applications. It is an extension of B-Tree and maintains sorted data in a manner that allows us for efficient insertion, deletion and search operations. The B+Trees stores all data in a leaf node while int
6 min read
TreeMap subMap() Method in Java with Examples
In Java, subMap() method of TreeMap class is used to return the part or portion of the map defined by the specified range of keys in the parameter. Any changes made in one or the other map will reflect the change in the other map. Syntax: Tree_Map.subMap(K startKey, K endKey) Parameters: The method
3 min read
TreeMap values() Method in Java with Examples
In Java, the values() method of the TreeMap class is present inside java.util package which is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the TreeMap. --> java.util package --> TreeMap class --> values() Method Syntax: T
2 min read
TreeMap floorEntry() Method in Java With Examples
The java.util.TreeMap.floorEntry() method is used to return a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key. Syntax: tree_map.floorEntry(K key) Parameters: This method takes one parameter key to be matched while mapping. Retur
2 min read
TreeMap firstEntry() Method in Java with Examples
TreeMap firstEntry() refers to the method used to retrieve the key-value pairs mapped with the lowest key value element that exists in the TreeMap, if there are no key-value pairs within the Map, simply returns null. The method name 'firstEntry()' explains itself that it will return entry having the
2 min read
Initialize a static Map using Stream in Java
In this article, a static map is created and initialized in Java using Stream. Static Map in Java A static map is a map which is defined as static. It means that the map becomes a class member and can be easily used using class. Stream In Java Introduced in Java 8, the Stream API is used to process
2 min read
TreeMap higherEntry() method in Java with Examples
The higherEntry() method of java.util.TreeMap class 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.Syntax: public Map.Entry higherEntry(K key) Parameters: This method takes the key as a parameter.Return Value:
2 min read
How to iterate over a TreeMap in Java?
Given a TreeMap, the task is to iterate this TreeMap in Java. The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. We cannot iterate a TreeMap directly using iterators, because TreeMap is not a Collection. So we will have to use TreeMap.entrySet() me
3 min read
TreeMap keySet() Method in Java with Examples
In Java, keySet() method of TreeMap class is present inside java.util package in Java is used to create a set out of the key elements contained in the treemap. It basically returns a set view of the keys or we can create a new set and store the key elements in them in ascending order. Since the set
3 min read