# 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
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.38716694712638855, "perplexity": 3352.0607599308646}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 10, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2019-51/segments/1575540529006.88/warc/CC-MAIN-20191210205200-20191210233200-00200.warc.gz"}