Is there a Java equivalent of Python's defaultdict?

后端 未结 8 1534
失恋的感觉
失恋的感觉 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> map = new DefaultHashMap(() -> new ArrayList<>());
    map.get(11).add("first");
    

    I hope that can be of help.

提交回复
热议问题