How can I convert flux element to a key map mono

673 Views Asked by At

So I have an object of contactId and I convert it to flux and then I query the contact details using each Id respectively and after that convert it to Mono using collectList method and map it to another object let's call it DomainContactDetails like this.

Flux.just(identifier.regContactId, identifier.billingContactId ,identifier.adminContactId, identifier.techContactId)
      .flatMap { resellerGetContact(it) }
      .collectList()
      .map { DomainContactDetails.fromList(it) }
      .toFuture()

Are there anyways to collect flux element into key map instead of list. for now I'm using index of list to indentify which data belongs to the property

data class DomainContactDetails(
  val registrantContact: ContactInfo,
  val billingContact: ContactInfo,
  val adminContact: ContactInfo,
  val techContact: ContactInfo
) {
  companion object {
    fun fromList(contacts: List<ContactInfo>) = DomainContactDetails(
      registrantContact = contacts[0],
      billingContact = contacts[1],
      adminContact = contacts[2],
      techContact = contacts[3]
    )
  }
}

I want it to be key map so it might be a bit better like this

fun fromKeyMap(contacts: Map<String, ContactInfo>) = DomainContactDetails(
  registrantContact = contacts["reg"],
  billingContact = contacts["bil"],
  adminContact = contacts["adm"],
  techContact = contacts["tec"]
)
1

There are 1 best solutions below

0
On

I'm not sure in your solution at all, but since you are asking about collecting to Map here is an answer. See Flux.collect() operator:

/**
 * Collect all elements emitted by this {@link Flux} into a container,
 * by applying a Java 8 Stream API {@link Collector}
 * The collected result will be emitted when this sequence completes.
 *
 * <p>
 * <img class="marble" src="doc-files/marbles/collectWithCollector.svg" alt="">
 *
 * @param collector the {@link Collector}
 * @param <A> The mutable accumulation type
 * @param <R> the container type
 *
 * <p><strong>Discard Support:</strong> This operator discards the intermediate container (see {@link Collector#supplier()} upon
 * cancellation, error or exception while applying the {@link Collector#finisher()}. Either the container type
 * is a {@link Collection} (in which case individual elements are discarded) or not (in which case the entire
 * container is discarded). In case the accumulator {@link BiConsumer} of the collector fails to accumulate
 * an element into the intermediate container, the container is discarded as above and the triggering element
 * is also discarded.
 *
 * @return a {@link Mono} of the collected container on complete
 *
 */
public final <R, A> Mono<R> collect(Collector<? super T, A, ? extends R> collector) {

So, probably you just need to utilize an existing Collectors.toMap() API.