How do I access nested HashMaps in Java?

后端 未结 10 788
再見小時候
再見小時候 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: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 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 smap = (Map) stageObj;
            Object[] skeys = Arrays.copyOfRange(keys, 1, keys.length);
            return pullNestedVal(smap, skeys);
        } else {
            return null;
        }
    }
    

提交回复
热议问题