MultikeyMap : Nested maps solution.
Hi everyone , recently I came accross a usecase where I had to map multiple keys against one value. So Juggling with this I came to know about MultiKeyMap of apache.
MultikeyMap is used to map multiple keys against one value . The purpose of this class is to avoid the need to write code to handle maps of maps. It simply implements java.io.Serializable, java.util.Map and IterableMap.
These provide get(), containsKey(), put() and remove() methods for individual keys which operate without extra object creation.This map is implemented as a decorator of a AbstractHashedMap which enables extra behaviour to be added easily.
[java]
import org.apache.commons.collections.map.MultiKeyMap
MultiKeyMap.decorate(new LinkedMap()) //creates an ordered map
MultiKeyMap.decorate(new LRUMap()) //creates an least recently used map.
MultiKeyMap.decorate(new ReferenceMap()) //creates a garbage collector sensitive map.
[/java]
Lets take an example for this:-
[java]
MultiKeyMap multiKeyMap=MultiKeyMap.decorate(new LinkedHahMap())
multiKeyMap.put("key1","key2","key3","value1") // Last parameter is value against defined keys.
multiKeyMap.put("key11","key22","key33","key44","value11")
multiKeyMap.put("key111","key222","key333","value111")
multiKeyMap.put("key1111","key2222","value1111")
[/java]
This is how we create a map with multiple keys. Now let’s see how to fetch value out of multiKeyMap for one combination of keys.
PS :- One point to note is you have to provide combination of key in the same sequence that you provided while puting into map.
[java]
String value1 = multiKeyMap.get("key1","key2","key3")
String value2 = multiKeyMap.get("key11","key22","key33","key44")
[/java]
During this learning I came to know about MultiKey which is again an another way to solve above use case.A MultiKey allows multiple map keys to be merged together. Example of MultiKeyMap With MultiKey :-
[java]
import org.apache.commons.collections.keyvalue.MultiKey
MultiKey multiKey=new MultiKey("key1","key2","key3")
MultikeyMap multiKeyMap=MultiKeyMap.decorator(new LinkedHashMap())
//Map map = new HashMap(); you can also use simple Map while using Multikey.
multiKeyMap.put(multiKey,"value1")
//To fetch value from map using multikey, we simply do as follows :-
multiKeyMap.get(multiKey)
[/java]
You can also access each key using index of key within MultiKey object. For Example :-
[java]
multikey.getKey(0) // output is ‘key1’
[/java]
I hope this blog was helpful and added useful content to your knowledge. For any queries you can comment below.
I dream of a day, a day when people test their code before putting it online and assuming it works …