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.

200_success
146k22 gold badges190 silver badges478 bronze badges
asked May 25, 2016 at 13:12
\$\endgroup\$

1 Answer 1

-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!

answered Jun 7, 2016 at 23:25
\$\endgroup\$
3
  • \$\begingroup\$ Please try to explain how this is an improvement of the existing code \$\endgroup\$ Commented Jun 8, 2016 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\$ Commented Jun 8, 2016 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\$ Commented Jun 8, 2016 at 21:23

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.