I have a double nested hashmap of hashmaps and want to check for key existence and place new values. Currently I am nesting if statements to check for key existence at each level. Is there a more efficient way to code this?
HashMap<Foo1, HashMap<Foo2, HashMap<Foo3, Double>>> my_map = new HashMap<Foo1, HashMap<Foo2, HashMap<Foo3, Double>>>();
if (my_map.containsKey(foo1key)) {
if (my_map.get(foo1key).containsKey(foo2key)) {
if (my_map.get(foo1key).get(foo2key).containsKey(foo3key)) {
return my_map.get(foo1key).get(foo2key).get(foo3key);
}
}
}
double foo3key = getValue();
// do the above steps again to put foo3key into map.
Most efficient way (assuming your values are always non-null) is as follows:
This exploits the following techniques:
This is all a bit messy though – if you do this kind of manipulation a lot then I would suggest factoring it out into a separate function, so that you can just do: