How do I access nested HashMaps in Java?

后端 未结 10 765
再見小時候
再見小時候 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:32

    Yes.

    See:

    public static void main(String args[]) {
    
        HashMap<String, HashMap<String, Object>> map = new HashMap<String, HashMap<String,Object>>();
        map.put("key", new HashMap<String, Object>());
        map.get("key").put("key2", "val2");
    
        System.out.println(map.get("key").get("key2"));
    }
    
    0 讨论(0)
  • 2020-12-01 09:33

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

    Map<String, Map<String, String>> map = new HashMap<String, Map<String,String>>();
    

    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");
    }
    
    0 讨论(0)
  • 2020-12-01 09:33

    I came to this StackOverflow page looking for a something ala valueForKeyPath known from objc. I also came by another post - "Key-Value Coding" for Java, but ended up writing my own.

    I'm still looking for at better solution than PropertyUtils.getProperty in apache's beanutils library.

    Usage

    Map<String, Object> json = ...
    public String getOptionalFirstName() {
        return MyCode.getString(json, "contact", "firstName");
    }
    

    Implementation

    public static String getString(Object object, String key0, String key1) {
        if (key0 == null) {
            return null;
        }
        if (key1 == null) {
            return null;
        }
        if (object instanceof Map == false) {
            return null;
        }
        @SuppressWarnings("unchecked")
        Map<Object, Object> map = (Map<Object, Object>)object;
        Object object1 = map.get(key0);
        if (object1 instanceof Map == false) {
            return null;
        }
        @SuppressWarnings("unchecked")
        Map<Object, Object> map1 = (Map<Object, Object>)object1;
        Object valueObject = map1.get(key1);
        if (valueObject instanceof String == false) {
            return null;
        }
        return (String)valueObject;
    }
    
    0 讨论(0)
  • 2020-12-01 09:34
    import java.util.*;
    public class MyFirstJava {
    public static void main(String[] args)
    {
      Animal dog = new Animal();
      dog.Info("Dog","Breezi","Lab","Chicken liver");
      dog.Getname();
      Animal dog2= new Animal();
      dog2.Info("Dog", "pumpkin", "POM", "Pedigree");
      dog2.Getname();
      HashMap<String,  HashMap<String, Object>> dogs = new HashMap<>();
      dogs.put("dog1", new HashMap<>() {{put("Name",dog.name); 
      put("Food",dog.food);put("Age",3);}});
      dogs.put("dog2", new HashMap<>() {{put("Name",dog2.name); 
      put("Food",dog2.food);put("Age",6);}});
      //dogs.get("dog1");
      System.out.print(dogs + "\n");
      System.out.print(dogs.get("dog1").get("Age"));
    

    } }

    0 讨论(0)
  • 2020-12-01 09:36

    You can do it like you assumed. But your HashMap has to be templated:

    Map<String, Map<String, String>> map = 
        new HashMap<String, Map<String, String>>();
    

    Otherwise you have to do a cast to Map after you retrieve the second map from the first.

    Map map = new HashMap();
    ((Map)map.get( "keyname" )).get( "nestedkeyname" );
    
    0 讨论(0)
  • 2020-12-01 09:36

    I hit this discussion while trying to figure out how to get a value from a nested map of unknown depth and it helped me come up with the following solution to my problem. It is overkill for the original question but maybe it will be helpful to someone that finds themselves in a situation where you have less knowledge about the map being searched.

    private static Object pullNestedVal(
            Map<Object, Object> vmap,
            Object ... keys) {
        if ((keys.length == 0) || (vmap.size() == 0)) {
            return null;
        } else if (keys.length == 1) {
            return vmap.get(keys[0]);
        }
    
        Object stageObj = vmap.get(keys[0]);
        if (stageObj instanceof Map) {
            Map<Object, Object> smap = (Map<Object, Object>) stageObj;
            Object[] skeys = Arrays.copyOfRange(keys, 1, keys.length);
            return pullNestedVal(smap, skeys);
        } else {
            return null;
        }
    }
    
    0 讨论(0)
提交回复
热议问题