# Finding the mean using RxJava

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

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!

• Please try to explain how this is an improvement of the existing code – Quill Jun 8 '16 at 9:14
• Am I not losing precision here by using Float? My code sample uses BigDecimal, in case you didn't notice. – Ragunath Jawahar Jun 8 '16 at 13:58
• 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. – Rodrigo Henriques Jun 8 '16 at 21:23