简体   繁体   中英

Iterate over HashMap in Project Reactor

I am getting tangled up with Java Reactor.

If I had some the following non-reactive code:

    Map<String, String> idToName = new HashMap<>();

    idToName.put("1", "John");
    idToName.put("2", "Harris");
    idToName.put("3", "Sally");
    idToName.put("4", "Mary");

    idToName.forEach((id, name) -> {
        System.out.println("id: " + name + " name: " + name);
    });

If I wanted to make this code Reactive. Say I want to call a method, called process, which takes the (key, value) from the HashMap:

    public Mono<String> process(String key, String val) {
        // do some processing
        return Mono.just(......);

The process returns a Mono

Can someone please show me how to write a reactive pipeline which would iterate over (key, value), call process, and return a List<Mono

Thanks

Miles.

All you need is Flux.fromIterable method:

Flux.fromIterable(idToName.entrySet()) //Flux of Entry<String, String>
        .flatMap(entry -> process(entry.getKey(), entry.getValue()))//Flux of String
        .doOnNext(entry -> System.out.println(entry))
        .subscribe();

Will create a Flux of Entry<String, String> by emitting the content from HashMap's entry set.

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