在java 8流中添加Bigdecimals [英] Adding Bigdecimals inside java 8 stream

查看:291
本文介绍了在java 8流中添加Bigdecimals的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一种方式是否比另一方式更有效。是否有更好的java 8方式来执行以下操作?

I would like to know if one way is more effecient than the other. Is there a better java 8 way to do the following operation ?

java 8 way

java 8 way

BigDecimal total = entries.parallelStream()
    .map(poec -> BigDecimal.valueOf(poec.getQuantity().longValue() * poec.getAdjustedUnitPrice().doubleValue()))
    .collect(Collectors.toList()).stream()
    .reduce(BigDecimal.ZERO, BigDecimal::add);

普通Java 7方式

    for (final EntryConsumed poec : entries) {
      total = total.add(BigDecimal.valueOf(poec.getQuantity().longValue() * poec.getAdjustedUnitPrice().doubleValue()));
    }


推荐答案

你有一些冗余代码您的Java 8解决方案。它可以简化为:

You have some redundant code in your Java 8 solution. It can be simplified to:

BigDecimal total = entries.parallelStream()
            .map(poec -> BigDecimal.valueOf(poec.getQuantity().longValue() * poec.getAdjustedUnitPrice().doubleValue()))
            .reduce(BigDecimal.ZERO, BigDecimal::add);

至于性能,您可以通过对两种解决方案进行基准测试来自行计算。

As for performance, you can calculate this yourself by benchmarking the two solutions.

这篇关于在java 8流中添加Bigdecimals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆