Is there a Java equivalent of Python's defaultdict?

后端 未结 8 1532
失恋的感觉
失恋的感觉 2021-02-05 00:05

In Python, the defaultdict class provides a convenient way to create a mapping from key -> [list of values], in the following example,



        
8条回答
  •  无人及你
    2021-02-05 00:28

    There is nothing that gives the behaviour of default dict out of the box. However creating your own default dict in Java would not be that difficult.

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    public class DefaultDict extends HashMap {
    
        Class klass;
        public DefaultDict(Class klass) {
            this.klass = klass;    
        }
    
        @Override
        public V get(Object key) {
            V returnValue = super.get(key);
            if (returnValue == null) {
                try {
                    returnValue = klass.newInstance();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
                this.put((K) key, returnValue);
            }
            return returnValue;
        }    
    }
    

    This class could be used like below:

    public static void main(String[] args) {
        DefaultDict> dict =
            new DefaultDict>(ArrayList.class);
        dict.get(1).add(2);
        dict.get(1).add(3);
        System.out.println(dict);
    }
    

    This code would print: {1=[2, 3]}

提交回复
热议问题