\$\begingroup\$
\$\endgroup\$
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
1 Answer 1
\$\begingroup\$
\$\endgroup\$
3
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
-
\$\begingroup\$ Please try to explain how this is an improvement of the existing code \$\endgroup\$Quill– Quill2016年06月08日 09:14:26 +00:00Commented Jun 8, 2016 at 9:14
-
1\$\begingroup\$ Am I not losing precision here by using
Float
? My code sample usesBigDecimal
, in case you didn't notice. \$\endgroup\$Ragunath Jawahar– Ragunath Jawahar2016年06月08日 13:58:31 +00:00Commented 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\$Rodrigo Henriques– Rodrigo Henriques2016年06月08日 21:23:54 +00:00Commented Jun 8, 2016 at 21:23
lang-java