Java checks the existence of the key in the double nested hash map

I have a double nested HashMap HashMap, which wants to check the existence of the key and place the new value At present, I am nesting if statements to check the existence of keys at each level Is there a more effective way to code?

HashMap<Foo1,HashMap<Foo2,HashMap<Foo3,Double>>> my_map = new HashMap<Foo1,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.

Solution

The most effective method (assuming that your value is always non null) is as follows:

HashMap<Foo2,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 utilizes the following technologies:

>If get() returns null, it means that the key does not exist (because null values are not allowed) > save the return value of the previous get for the next search, so you don't need to link together

This is a bit messy – if you do a lot of this, I suggest breaking it down into a separate function so that you can do this:

double value = getNestedValue(my_map,foo1Key,foo2Key,foo3Key);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>