java streams: accumulated collector

Currently, that's my code:

Iterable<Practitioner> referencedPractitioners = this.practitionerRepository.findAllById(
    Optional.ofNullable(patient.getPractitioners())
        .map(List::stream)
        .orElse(Stream.of())
        .map(Reference::getIdPart)
        .collect(Collectors.toList())
    );

As you can see, I'm using this.practitionerRepository.findAllById(Iterable<String> ids), in order to get all using a single communication with database.

I was trying to change it using this:

Optional.ofNullable(patient)
    .map(org.hl7.fhir.r4.model.Patient::getPractitioners)
    .map(List::stream)
    .orElse(Stream.of())
    .map(Reference::getIdPart)
    .collect(????????);

How could I use this.practitionerRepository.findAllById(Iterable<String> ids) into a custom collector in collect method?

Remember I need to get all entities at once. I can't get them one by one.


You can use Collectors.collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher) specialized collector for that.

  1. Make a list of IDs using the Collector.toList() collector and then
  2. Pass a reference practitionerRepository::findAllById to convert from List<String> to Iterable<Practitioner>

Example:

Iterable<Practitioner> referencedPractitioners = Optional.ofNullable(patient)
      .map(Patient::getPractitioners)
      .map(List::stream)
      .orElseGet(Stream::of)
      .map(Reference::getIdPart)
      .collect(Collectors.collectingAndThen(toList(), practitionerRepository::findAllById));