問題描述
我相信接下來我可以在 listOfPricedObjects 上使用一個流操作:
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)
如何在 myList 中填寫價格并使用流一次計算價格總和?謝謝
How I can fill myList with prices and calculate sum of prices using stream one time? Thanks
UPD:結果我需要用價格填充 myList 并用 sum 變量求和.但不是使用 stream() 兩次.
UPD: As the result I need myList filled with prices and sum variable with sum. But not with usding stream() twice for that.
推薦答案
您可以使用 peek
并在應用縮減的同時添加到新的 list
You can use peek
and add to a new list
while applying the reduction
List<BigDecimal> newList = new ArrayList<>();
BigDecimal sum = list.stream()
.map(PricedObject::getPrice)
.peek(newList::add)
.reduce(BigDecimal.ZERO, BigDecimal::add);
如果您有興趣將 parallelStream
與非并發集合一起使用,請查看 Tunaki 的答案,這是有意義的,因為 sum 是一個令人尷尬的并行任務.
Please look at Tunaki answer if you interested in using a parallelStream
with a non concurrent collection which makes sense since sum is an embarrassingly parallel task.
這篇關于Java 8 Stream 將元素添加到列表和求和中的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!