Search code examples
javalambdajava-streamfunctional-java

Java 8 Lambdas flatmapping, groupingBy and mapping to get a Map of T and List<K>


Here's what I have so far:

Map<Care, List<Correlative>> mapOf = quickSearchList
                .stream()
                .map(QuickSearch::getFacility)
                .collect(Collectors.flatMapping(facility -> facility.getFacilityCares().stream(),
                    Collectors.groupingBy(FacilityCare::getCare,
                        Collectors.mapping(c -> {
                            final Facility facility = new Facility();
                            facility.setId(c.getFacilityId());
                            return Correlative.createFromFacility(facility);
                        }, Collectors.toList()))));

I have a list of Quick Searches to begin with. Each item in the quick search has a single facility as in:

public class QuickSearch {
  Facility facility;
}

In every Facility, there's a List of FacilityCare as in:

public class Facility {
  List<FacilityCare> facilityCares;
}

And finally, FacilityCare has Care property as in:

public class FacilityCare {
   Care care;
}

Now, the idea is to convert a List of QuickSearch to a Map of <Care, List<Correlative>>. The code within the mapping() function is bogus, in the example above. FacilityCare only has facilityID and not Facility entity. I want the facility object that went as param in flatMapping to be my param again in mapping() function as in:

Collectors.mapping(c -> Correlative.createFromFacility(facility)) 

where "facility" is the same object as the one in flatMapping.

Is there any way to achieve this? Please let me know if things need to be explained further.

Edit: Here's a solution doesn't fully utilize Collectors.

final Map<Care, List<Correlative>> mapToHydrate = new HashMap<>();

 quickSearchList
  .stream()
  .map(QuickSearch::getFacility)
  .forEach(facility -> {
    facility.getFacilityCares()
      .stream()
      .map(FacilityCare::getCare)
      .distinct()
      .forEach(care -> {
        mapToHydrate.computeIfAbsent(care, care -> new ArrayList<>());
        mapToHydrate.computeIfPresent(care, (c, list) -> {
          list.add(Correlative.createFromFacility(facility));
          return list;
        });
      });
    });
      

Solution

  • Sometimes, streams are not the best solution. This seems to be the case, because you are losing each facility instance when going down the pipeline.

    Instead, you could do it as follows:

    Map<Care, List<Correlative>> mapToHydrate = new LinkedHashMap<>();
    quickSearchList.forEach(q -> {
        Facility facility = q.getFacility();
        facility.getFacilityCares().forEach(fCare -> 
            mapToHydrate.computeIfAbsent(fCare.getCare(), k -> new ArrayList<>())
                        .add(Correlative.createFromFacility(facility)));
    });
    

    This uses the return value of Map.computeIfAbsent (which is either the newly created list of correlatives or the already present one).

    It is not clear from your question why you need distinct cares before adding them to the map.


    EDIT: Starting from Java 16, you might want to use Stream.mapMulti:

    Map<Care, List<Correlative>> mapToHydrate = quickSearchList.stream()
        .map(QuickSearch::getFacility)
        .mapMulti((facility, consumer) -> facility.getFacilityCares()
            .forEach(fCare -> consumer.accept(Map.entry(fCare.getCare(), facility))))
        .collect(Collectors.groupingBy(
            e -> e.getKey(), 
            Collectors.mapping(
                e -> Correlative.createFromFacility(e.getValue()),
                Collectors.toList())));