如何将通量元素转换为键映射单声道
Posted
技术标签:
【中文标题】如何将通量元素转换为键映射单声道【英文标题】:How can I convert flux element to a key map mono 【发布时间】:2021-07-11 16:11:41 【问题描述】:所以我有一个contactId对象,我将其转换为flux,然后我分别使用每个Id查询联系人详细信息,然后使用collectList方法将其转换为Mono并将其映射到另一个对象,让我们称之为DomainContactDetails。
Flux.just(identifier.regContactId, identifier.billingContactId ,identifier.adminContactId, identifier.techContactId)
.flatMap resellerGetContact(it)
.collectList()
.map DomainContactDetails.fromList(it)
.toFuture()
有没有办法将通量元素收集到键映射而不是列表中。现在我正在使用列表索引来识别哪些数据属于该属性
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]
)
我希望它是键映射,这样可能会更好一些
fun fromKeyMap(contacts: Map<String, ContactInfo>) = DomainContactDetails(
registrantContact = contacts["reg"],
billingContact = contacts["bil"],
adminContact = contacts["adm"],
techContact = contacts["tec"]
)
【问题讨论】:
【参考方案1】:我完全不确定您的解决方案,但是由于您询问是否要收集到Map
,所以这是一个答案。见Flux.collect()
运营商:
/**
* 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" >
*
* @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)
所以,您可能只需要利用现有的Collectors.toMap()
API。
【讨论】:
以上是关于如何将通量元素转换为键映射单声道的主要内容,如果未能解决你的问题,请参考以下文章
java - 如何在Java响应式中为通量/单声道调用多个服务?