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)
{
MultiMap<Character, Integer> multiMap =
new
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
);
System.out.println(
"The Key and values in the MultiMap are: "
);
System.out.println(multiMap);
System.out.println(
"\nSize Of multiMap : "
+ multiMap.size());
multiMap.remove(
'A'
,
4
);
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());
multiMap.removeAll(
'D'
);
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());
System.out.println(
"Values in the MultiMap associated with the key are: "
);
System.out.println(multiMap.get(
'B'
));
System.out.println(
"\nIs 'A' Present?"
+ multiMap.containsKey(
'A'
));
System.out.println(
"\nKey and Values in MultiMap : "
);
System.out.println(multiMap);
}
}