I believe I can do next using one stream operation on listOfPricedObjects:
List<BigDecimal> myList = new ArrayList();
myList = listOfPricedObjects.stream().map(PricedObject::getPrice).collect(Collectors.toList());
BigDecimal sum = listOfPricedObjects.stream().map(PricedObject::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add)
How I can fill myList with prices and calculate sum of prices using stream one time?
Thanks
UPD: As the result I need myList filled with prices and sum variable with sum. But not with usding stream() twice for that.
Best Answer
What you want here is to collect your elements inside 2 collectors: the first one would collect into a list, and the second one would sum the price.
Since there are no such collectors in the Stream API itself, we can easily construct our own. Let's create a class
ResultHolder
that will hold the result of the Stream pipeline: this is the list of decimals and the sum.Finally, we can use it with:
This will work in a parallel pipeline and will keep the initial order of the list, contrary to the other answers.