简体   繁体   中英

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.

Basically I would like to group a certain stream and then obtain the hash-map such as 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. 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 ? It accepts Collector , the same type as Stream uses. There is also Flux#collectMap .

Plus, in case you need to stream such map, you can use 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.

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