chocksaway
chocksaway

Reputation: 900

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.

Upvotes: 0

Views: 1555

Answers (1)

lkatiforis
lkatiforis

Reputation: 6255

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.

Upvotes: 2

Related Questions