import
java.util.*;
class
MultiMap {
private
TreeMap<Character, List<Integer> > treeMap;
private
int
size;
public
MultiMap()
{
treeMap =
new
TreeMap<Character, List<Integer> >();
size =
0
;
}
public
void
put(
char
key,
int
value)
{
treeMap.computeIfAbsent(key, k ->
new
ArrayList<>())
.add(value);
++size;
}
public
List<Integer> get(
char
key)
{
return
this
.containsKey(key)
? treeMap.get(key)
:
new
ArrayList<Integer>();
}
public
void
removeAll(
char
key)
{
if
(
this
.containsKey(key)) {
size -= treeMap.get(key).size();
treeMap.remove(key);
}
}
public
boolean
remove(
char
key,
int
value)
{
boolean
isKeyPresent =
this
.containsKey(key);
if
(!isKeyPresent) {
return
false
;
}
boolean
isValuePresent
= treeMap.get(key).contains(value);
if
(isValuePresent) {
treeMap.get(key).remove(
new
Integer(value));
--size;
}
return
isKeyPresent && isValuePresent;
}
public
int
size() {
return
this
.size; }
public
boolean
containsKey(
char
key)
{
return
treeMap.containsKey(key);
}
@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)
{
MultiMap 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(
"Key and Values in MultiMap : "
);
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(
"Key and Values in MultiMap : "
);
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(
"Key and Values in MultiMap : "
);
System.out.println(multiMap);
System.out.println(
"\nSize Of multiMap : "
+ multiMap.size());
System.out.println(
"Values in MultiMap associated with key: "
);
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);
}
}