0
\$\begingroup\$

I'm learning RxJava and this is what I attempted to find the mean of 'n' transactions.

List<Transaction> transactions = TransactionsStore.getTransactions();
BigDecimal nTransactions = new BigDecimal(transactions.size());
Observable.from(transactions)
        .map(transaction -> transaction.amount)
        .reduce(BigDecimal::add)
        .map(total -> total.divide(nTransactions, 2, BigDecimal.ROUND_DOWN))
        .map(mean -> String.format("The mean is %s", mean.toPlainString()))
        .subscribe(System.out::println);

I'd like to know if this could be done better.

\$\endgroup\$
-1
\$\begingroup\$

Using RxJava-Math you can achieve the same result by this way:

List<Transaction> transactions = createRandomTransactions(10);

final Observable<Float> amountStream = Observable.from(transactions)
        .map(transaction -> transaction.amount);

MathObservable.averageFloat(amountStream)
        .map(mean -> String.format(Locale.US, "The mean is %.2f", mean))
        .subscribe(System.out::println);

Hope that helps!

\$\endgroup\$
  • \$\begingroup\$ Please try to explain how this is an improvement of the existing code \$\endgroup\$ – Quill Jun 8 '16 at 9:14
  • 1
    \$\begingroup\$ Am I not losing precision here by using Float? My code sample uses BigDecimal, in case you didn't notice. \$\endgroup\$ – Ragunath Jawahar Jun 8 '16 at 13:58
  • \$\begingroup\$ I'm just showing a different way to achieve the mean. I noticed that you are using BigDecimal, but you don't explicit defined this as a strong requirement in your question. \$\endgroup\$ – Rodrigo Henriques Jun 8 '16 at 21:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.