How do I access nested HashMaps in Java?

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

    If you plan on constructing HashMaps with variable depth, use a recursive data structure.

    Below is an implementation providing a sample interface:

    class NestedMap {
    
        private final HashMap child;
        private V value;
    
        public NestedMap() {
            child = new HashMap<>();
            value = null;
        }
    
        public boolean hasChild(K k) {
            return this.child.containsKey(k);
        }
    
        public NestedMap getChild(K k) {
            return this.child.get(k);
        }
    
        public void makeChild(K k) {
            this.child.put(k, new NestedMap());
        }
    
        public V getValue() {
            return value;
        }
    
        public void setValue(V v) {
            value = v;
        }
    }
    

    and example usage:

    class NestedMapIllustration {
        public static void main(String[] args) {
    
            NestedMap m = new NestedMap<>();
    
            m.makeChild('f');
            m.getChild('f').makeChild('o');
            m.getChild('f').getChild('o').makeChild('o');
            m.getChild('f').getChild('o').getChild('o').setValue("bar");
    
            System.out.println(
                "nested element at 'f' -> 'o' -> 'o' is " +
                m.getChild('f').getChild('o').getChild('o').getValue());
        }
    }
    

提交回复
热议问题