简体   繁体   中英

Reduce List<T> using BiFunction<T, T, Mono<T>>

I have List<T> , I need to reduce it using BiFunction<R, T, Mono<R>> aggregator.

So I need to chain those monos ( Mono<R> ) How this can be done using project reactor?

UPDATE: For example, I have a list with item1, item2 etc... I have a function Mono<R> reduce(T item, R acc)

I need something like this: reduce(item1, startAcc).flatMap(acc -> reduce(item2, acc)).flatMap(acc -> reduce(item3, acc)) etc.

I can implement this using recursion, but I get StackOverflowError if the list is long enough

You should simply use the reduce method available on Flux . Sample code below:

public void reduceTest() {

    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    Flux<Integer> numberFlux = Flux.fromIterable(numbers);

    Double initial = 2.5;
    BiFunction<Double, Integer, Double> multiply = (doubleNumber, numberInt) -> doubleNumber * numberInt;

    Mono<Double> floatResult = numberFlux.reduce(initial, multiply);        
    floatResult.subscribe(System.out::println);

}

Please refer the Java Docs at https://projectreactor.io/docs/core/release/api/index.html?reactor/core/publisher/Mono.html

在此处输入图片说明

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