This post will introduce you to different version of Map called “MultiValuedMap”.
This map was added in Apache Commons Collection framework.
This map is similar to java.util.Map and at the same different.
The similarities are
1) Both map hold key value pair
The differences are
2) In java.util.Map the value is a single value whereas in MultiValuedMap, the value is a collection of values.
Below is the example of MultiValuedMap collection
Main Code
1 import java.util.Collection;
2 import java.util.Map;
3
4 import org.apache.commons.collections4.MultiValuedMap;
5 import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;
6
7 public class Example6 {
8 public static void main(String[] args) {
9 MultiValuedMap map = new ArrayListValuedHashMap();
10 map.put(1, "A");
11 map.put(1, "B");
12 map.put(1, "C");
13 map.put(2, "a");
14 map.put(2, "B");
15
16 System.out.println("The values of key 1");
17 Collection coll = map.get(1);
18 for(String data : coll) {
19 System.out.println(data);
20 }
21
22 System.out.println("The values of key 2");
23 coll = map.get(2);
24 for(String data : coll) {
25 System.out.println(data);
26 }
27
28 System.out.println("The values of key 1 after removing value B");
29 map.removeMapping(Integer.valueOf(1), "B");
30 coll = map.get(1);
31 for(String data : coll) {
32 System.out.println(data);
33 }
34
35 System.out.println("The entire map collection");
36 Collection<Map.Entry> col2 = map.entries();
37 for(Map.Entry entry : col2) {
38 System.out.println(entry.getKey() + ":" + entry.getValue());
39 }
40 }
41 }
Explanation
At line 9, we create an instance of ArrayListValuedHashMap (a class implementing MultiValuedMap interface).
From line 10 to 14, we populate the map.
From line 17 to 20, we print the values of key 1. Note the return value of map.get is a collection of string values.
From line 22 to 26, we print the values of key 2.
At line 29, we remove the key value pair {1, “B”} by calling removeMapping method of the MultiValuedMap interface and then again print the values of key 1.
From line 36 to 39, we print the entire map data.
Output
The values of key 1
A
B
C
The values of key 2
a
B
The values of key 1 after removing value B
A
C
The entire map collection
1:A
1:C
2:a
2:B