gewizz
gewizz

Reputation: 539

java checking for key existence in double nested hashmaps

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.

Upvotes: 4

Views: 2813

Answers (1)

mikera
mikera

Reputation: 106351

Most efficient way (assuming your values are always non-null) is as follows:

HashMap<Foo2, HashMap<Foo3, Double>> map2 = my_map.get(foo1Key);
if(map2!=null) {
  HashMap<Foo3, Double> map3 = map2.get(foo2Key);
  if (map3!=null) {
    Double value = map3.get(foo3Key);
    if (value!=null) {
      return (double)value;
    } else {
      // add value to map3, or whatever
    }
  }
}

This exploits the following techniques:

  • If get() returns null, you know that the key does not exist (since null values are not allowed)
  • Saving the return value of the previous get for the next lookup, so that you don't need to chain gets together

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:

double value = getNestedValue(my_map,foo1Key,foo2Key,foo3Key);

Upvotes: 1

Related Questions