Adding Bigdecimals inside java 8 stream

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-08 14:06:46

问题


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

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

Normal Java 7 way

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

回答1:


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.



来源:https://stackoverflow.com/questions/37659181/adding-bigdecimals-inside-java-8-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!