简体   繁体   English

java检查双嵌套哈希映射中的密钥存在

[英]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. 我有一个双嵌套的hashmaps hashmap,想要检查密钥存在并放置新值。 Currently I am nesting if statements to check for key existence at each level. 目前我正在嵌套if语句来检查每个级别的密钥存在。 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: 最有效的方法(假设您的值始终为非null)如下:

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) 如果get()返回null,则表示该密钥不存在(因为不允许使用空值)
  • Saving the return value of the previous get for the next lookup, so that you don't need to chain gets together 保存上一个get的返回值以进行下一次查找,这样您就不需要链接到一起了

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM