Is there a Java equivalent of Python's defaultdict?

后端 未结 8 1536
失恋的感觉
失恋的感觉 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:45

    I wrote the library Guavaberry containing such data structure: DefaultHashMap.

    It is highly tested and documented. You can find it and integrate it pretty easily via Maven Central.

    The main advatage is that it uses lambda to define the factory method. So, you can add an arbitrarly defined instance of a class (instead of relying on the existence of the default constructor):

    DefaultHashMap<Integer, List<String>> map = new DefaultHashMap(() -> new ArrayList<>());
    map.get(11).add("first");
    

    I hope that can be of help.

    0 讨论(0)
  • 2021-02-05 00:46

    You can use MultiMap from Apache Commons.

    0 讨论(0)
提交回复
热议问题