Rather than making a map of maps (Map<K1,Map<K2,V>>
), I find it often easier to make a map that uses a composite key : Map<Key<K1, K2>, V>
.
You could make a generic Key
class for this, or make a dedicated class on a per case basis since sometimes this key makes sense business-wise : e.g. Buyer - Seller -> Contract.
Nevertheless, if you use a generic Key
class (make sure equals()
and hashCode()
are implemented properly), you could still have use for a variant of your MapMap
, that takes individual K1
and K2
objects and combines them into a key behind the scenes. But I think you'll find that a Key
class with a static factory method is easy enough to use :
getting :
V value = map.get(key(k1, k2));
or putting :
map.put(key(k1, k2), value);