How do I access nested HashMaps in Java?

后端 未结 10 772
再見小時候
再見小時候 2020-12-01 09:28

I have a HashMap in Java, the contents of which (as you all probably know) can be accessed by

HashMap.get(\"keyname\");

If a have a HashMap

10条回答
  •  暖寄归人
    2020-12-01 09:33

    As others have said you can do this but you should define the map with generics like so:

    Map> map = new HashMap>();
    

    However, if you just blindly run the following:

    map.get("keyname").get("nestedkeyname");
    

    you will get a null pointer exception whenever keyname is not in the map and your program will crash. You really should add the following check:

    String valueFromMap = null;
    if(map.containsKey("keyname")){
      valueFromMap = map.get("keyname").get("nestedkeyname");
    }
    

提交回复
热议问题