简体   繁体   中英

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM