[英]Collecting GroupFlux into a Hashmap by the keys
I've recently started using Project Reactor and I've come up with a scenario I can't seem to figure out. 我最近开始使用Project Reactor,并且提出了一个似乎无法弄清的方案。
Basically I would like to group a certain stream and then obtain the hash-map such as grouping key -> List of grouped values
. 基本上,我想对某个流进行分组,然后获取哈希图,例如grouping key -> List of grouped values
。 I've been playing around with the API but the furthest I've got is either obtaining the values, or the keys or the count, but not the data structure I want. 我一直在使用API,但是我获得的最远的要么是获取值,键,计数,要么不是我想要的数据结构。 This would be the code, for example, to obtain the values: 例如,这将是获得值的代码:
var elements = new ArrayList<Integer>();
Flux.just(-1, -2, -3, 1, 2, 3)
.groupBy(val -> val.compareTo(0))
.flatMap(Flux::collectList)
.subscribe(elements::addAll);
The test I would like to pass is the following: 我想通过的测试如下:
@Test
public void groupBy() {
var elements = new HashMap<Integer, List<Integer>>();
Flux.just(-1, -2, -3, 1, 2, 3)
.groupBy(val -> val.compareTo(0))
// Do something here ...
.subscribe(...);
assertThat(elements).containsKeys(-1, 1);
assertThat(elements.get(-1)).containsExactly(-1, -2, -3);
assertThat(elements.get(1)).containsExactly(1, 2, 3);
}
How could I achieve the latter? 我如何实现后者?
Have you considered using Flux#connect ? 您是否考虑过使用Flux#connect ? It accepts Collector
, the same type as Stream
uses. 它接受Collector
,与Stream
使用的类型相同。 There is also Flux#collectMap
. 还有Flux#collectMap
。
Plus, in case you need to stream such map, you can use Flux#scan . 另外,如果您需要流式传输此类地图,则可以使用Flux#scan 。
groupBy
is helpful when you need to "route" your signals by key and have a Flux
by key, but it is not designed to be used for creating collections of data. 当您需要按键“路由”信号并按键获取Flux
时, groupBy
会很有帮助,但它并非设计用于创建数据集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.