问题
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