title: How to sum multiple values in a Flux?
body: <p>I have expenses data. I need a model that includes the total expense amount, total paid expense amount, and expenses list. For this purpose, I wrote a function named <code>createExpenseSummaryReport</code>.</p>
  <pre class="lang-java prettyprint-override"><code>List&lt;ExpenseModel&gt; expensesModel = Arrays.asList(
          new ExpenseModel(&quot;Expense1&quot;, 121.687, 31.89),
          new ExpenseModel(&quot;Expense2&quot;, 78.03, 72.5),
          new ExpenseModel(&quot;Expense3&quot;, 102.014, 102.014),
          new ExpenseModel(&quot;Expense4&quot;, 100.0, 45.42)
      );
   
  ....
   public static ExpenseReportSummary createExpenseSummaryReport(List&lt;ExpenseModel&gt; expensesModel) {
      BigDecimal totalExpense = BigDecimal.ZERO;
      BigDecimal totalPaidExpense = BigDecimal.ZERO;
      for (ExpenseModel expense : expensesModel) {
        totalExpense = totalExpense.add(BigDecimal.valueOf(expense.getAmount()));
        totalPaidExpense =totalPaidExpense.add(BigDecimal.valueOf(expense.getPaidAmount()));
      }
      return new ExpenseReportSummary(expensesModel, totalExpense, totalPaidExpense);
    }
  </code></pre>
  <p>In a real project, I have a repository named <code>IncomeExpenseRepository</code>. This repository has this method that returns <code>Flux</code> income expenses.</p>
  <pre class="lang-java prettyprint-override"><code>Flux&lt;IncomeExpense&gt; byDateContaining = incomeExpenseRepository.findAllByDateContaining(
          request.getPeriod());
  </code></pre>
  <p>I need a <code>createExpenseSummaryReport</code> service in a reactive way. <code>createExpenseSummaryReport</code> includes income-expense list, total income amount, and total paid element. For this purpose, I am trying to complete the below function.</p>
  <pre><code>@Override
  public Mono&lt;IncomeExpenseSummaryReport&gt; getIncomeExpenseReportByPeriod(
  GetIncomeExpenseReportRequest request) {
  
      AtomicReference&lt;BigDecimal&gt; totalExpenseAmount = new AtomicReference&lt;&gt;(BigDecimal.ZERO);
      AtomicReference&lt;BigDecimal&gt; totalPaidExpenseAmount = new AtomicReference&lt;&gt;(BigDecimal.ZERO);
      
      incomeExpenseRepository.findAllByDateContaining(
              request.getPeriod())
          .doOnEach(d -&gt; {
            IncomeExpense incomeExpense = d.get();
            totalExpenseAmount.getAndSet(BigDecimal.valueOf(incomeExpense.getAmount()));
            if (&quot;paid&quot;.equals(incomeExpense.getPaymentStatus())) {
              totalPaidExpenseAmount.getAndSet(BigDecimal.valueOf(incomeExpense.getAmount()));
            }
          });
  
  
      return Flux.empty();
  
    }
  
  </code></pre>