【问题标题】:How to convert of Stream of Mono to Flux or reduce a stream of Mono to a Mono using sum operation如何使用 sum 操作将 Mono 流转换为 Flux 或将 Mono 流减少为 Mono
【发布时间】:2021-05-10 01:34:57
【问题描述】:

我的代码如下。我需要从 mongo db 获取每次旅行的票价,然后将每次旅行的所有票价相加得到总票价。我被一串我不知道如何阅读的 Mono 困住了。我尝试将其转换为 Flux,但我得到了 Flux,这不是我想要的。请帮忙!!或者我们如何才能将 Mono 的 Stream 简化为 Mono?

private int calculateDailyRate(final Entry<LocalDate, List<Trip>> entry) {
        int dailyFare = 0;
        List<Trip> trips = entry.getValue();
        // Get the fare for each trip, and then sum up the list of fares to get the daily total fare        
        trips.stream().map(trip->fareLookupRepo.getFareRules(trip.getSecondOfDay(), trip.getTripDate().getDayOfWeek().getValue(),
                    trip.getFromZone(), trip.getToZone()).sort(Comparator.comparing(FareRule::getRate)).next().map(FareRule::getRate));
        return dailyFare;
    }

'''

【问题讨论】:

    标签: spring-webflux


    【解决方案1】:

    我不确定你的逻辑是否正确,因为你可以与整体约会。

    但这里是提示如何做你试图达到的目标。

      return Flux.fromIterable(trips)
                .flatMap(trip-> fareLookupRepo.getFareRules(trip.getSecondOfDay(), trip.getTripDate().getDayOfWeek().getValue(),
                        trip.getFromZone(), trip.getToZone())
                .flatMap(trip-> Mono.just(trip.getRate())))
                .reduce(0, (x1, x2)-> x1 + x2)
    

    注意:fareLookupRepo.getFareRules 它应该返回单声道

    【讨论】:

    • 谢谢!!这似乎行得通。我对其进行了如下修改以使其正常工作: Flux.fromIterable(trips).flatMap(trip->getMatchingFareRule(trip).map(FareRule::getRate)).reduce(0, (x1, x2)-> x1 + x2 ) 其中 getMatchingFareRule 返回 Mono
    • 乐于提供帮助 :) 如果有帮助,请接受我的回答 ;) @Gayathri
    猜你喜欢
    • 1970-01-01
    • 2020-01-28
    • 2017-12-27
    • 1970-01-01
    • 2021-07-27
    • 2020-10-04
    • 2017-06-19
    • 2022-08-19
    • 1970-01-01
    相关资源
    最近更新 更多