Map with Composite key

In Maps we always use one key object to uniquely identify an entry.

We never combined a collection of keys to create one composite key and use it to uniquely identify an entry.

But with help of MultiKey class available in Apache Common Collections framework, we can create a composite key to uniquely identify an entry.

Below is an example

Main Code

1  import java.util.HashMap;
2  import java.util.Map;
4  import org.apache.commons.collections4.keyvalue.MultiKey;
6  public class Example7 {
7   public static void main(String[] args) {
8       Map<MultiKey, String> map = new HashMap<MultiKey, String>();
10      MultiKey multiKey1 = new MultiKey("Key1.1","Key1.2");
11      MultiKey multiKey2 = new MultiKey("Key2.1","Key2.2");
12      MultiKey multiKey3 = new MultiKey("Key3.1","Key3.2");
14      map.put(multiKey1, "value1");
15      map.put(multiKey2, "value2");
16      map.put(multiKey3, "value3");
18      for(MultiKey key : map.keySet()) {
19          System.out.println(map.get(key));
20      }
21  }
22 }

In the above code I create the map in the usual may except the key class will MultiKey.

From line 10 to 12 I create three MultiKey instance as keys.

From line 14 to 16 I populate the map using the MultiKey instances as keys.

At line 19 I use the MultiKey to retrieve the values.

The MultiKey class combine all the keys in its instance to compute a hashcode.



Leave a Reply