简体   繁体   English

在 Project Reactor 中迭代 HashMap

[英]Iterate over HashMap in Project Reactor

I am getting tangled up with Java Reactor.我越来越纠结于 Java 反应堆。

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:假设我想调用一个名为 process 的方法,它从 HashMap 中获取(键,值):

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

The process returns a Mono该过程返回一个 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有人可以告诉我如何编写一个反应式管道,它会迭代(键、值)、调用进程并返回一个 List<Mono

Thanks谢谢

Miles.迈尔斯。

All you need is Flux.fromIterable method:您只需要 Flux.fromIterable 方法:

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.将通过从 HashMap 的条目集中发出内容来创建Entry<String, String>的 Flux。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM