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());
        .map(transaction -> transaction.amount)
        .map(total -> total.divide(nTransactions, 2, BigDecimal.ROUND_DOWN))
        .map(mean -> String.format("The mean is %s", mean.toPlainString()))

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


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);

        .map(mean -> String.format(Locale.US, "The mean is %.2f", mean))

Hope that helps!

| improve this answer | |
  • \$\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.