Differences between Collectors.toMap() and Collectors.groupingBy() to collect into a Map

前端 未结 4 1540
傲寒
傲寒 2021-02-01 16:10

I want to create a Map from a List of Points and have inside the map all entries from the list mapped with the same parentId such as

4条回答
  •  醉话见心
    2021-02-01 16:50

    It is quite often true that a map from object.field to Collection of objects that share this field is better stored in a Multimap (Guava has a nice implementation for a multimap). If you don't NEED the multimap to be mutable (which should be the desired case), you can use

    Multimaps.index(chargePoints, Point::getParentId);
    

    If you must use a mutable map, you can either implement a collector (as demonstrated here: https://blog.jayway.com/2014/09/29/java-8-collector-for-gauvas-linkedhashmultimap/) or use a for loop (or forEach) to populate an empty, mutable multimap.

    A multimap gives you additional functionality that you normally need when you use a map from field to collection of objects sharing a field (like the count of total objects).

    A mutable multimap also makes it easier to add and remove elements to the map (without being concerned with the edge cases).

提交回复
热议问题