java Webflux:累积&详细信息

zyfwsgd6  于 2023-06-28  发布在  Java
关注(0)|答案(1)|浏览(90)

我是webflux的新手,我正在尝试转换以下代码:

@Getter
public class Stock {
    private int value;
    private String productNumber;
    public Stock(int value, String productNumber){
        this.value = value;
        this.productNumber = productNumber;
    }
}

@Getter
public class StockResponse {
    private int value;
    private String productNumber;
    public StockResponse(int value, String productNumber){
        this.value = value;
        this.productNumber = productNumber;
    }
    public StockResponse(Stock stock){
        this.value = stock.getValue();
        this.productNumber = stock.getProductNumber();
    }

    public void add(int value){
        this.value += value;
    }
    
}

public List<StockResponse> findStockResponsesDetailsAndTotal() {
    List<StockResponse> stocksResponses = new ArrayList();
    List<Stock> stocks = stockRepository.findAll();
    StockResponse total = new StockResponse(0, "Total");
    stocks.forEach(stock -> {
        total.add(stock.getValue());
        stocksResponses.add(new StockResponse(stock));
    });
    stocksResponses.add(total);
    return stocksResponses;
}

下面是我的代码:

stockRepository.findAll()
  .map(StockResponse::convert)

我有点迷失了关于“总”,我知道,我可以做一个减少通量,但我会失去所有的细节,这样做

toiithl6

toiithl61#

我发现将total结果作为列表中的最后一个元素添加,而不是在一侧包含total,在另一侧包含元素的专用类,这有点奇怪。
这里有一段代码:

Mono<List<StockResponse>> responses = findAll()
    .map(StockResponse::new).collectList().map(allStock -> {
        StockResponse total = new StockResponse(0, "Total");
        allStock.forEach(stock -> total.add(stock.value));
        List<StockResponse> result = new ArrayList<>(allStock);
        result.add(total);
        return result;
});

相关问题