Hi, I'm trying to remind myself streams and started small project with shopping cart. However I don't know how to get total price of items, which I want to count via Stream API.
How to get into collection, use getPrice() method (method of ShoppingItem, which is the key in HashMap), multiply it by quantity (Value of Hashmap) and get sum of this multiplications?
Here is shrunk down code:
You can't iterate a Map. only one of the three sets you can get out of it. You can get access to those three sets via three of the Map's methods. You can use the map() mathod to take the price and count and produce a number. If you have the price as a primitive you may be able to get a Stream of primitives with a method called mapToXYZ() and use its sum() method, otherwise you would have to write a Collector with its three parts yourself, or use the reduce() method which you will find examples of in the package documentation.
Show us what you have tried and tell us how it is going. This is one of the circumstances where it is much easier to use an IDE than the command line.
Campbell Ritchie wrote:You can't iterate a Map. only one of the three sets you can get out of it. You can get access to those three sets via three of the Map's methods. You can use the map() mathod to take the price and count and produce a number. If you have the price as a primitive you may be able to get a Stream of primitives with a method called mapToXYZ() and use its sum() method, otherwise you would have to write a Collector with its three parts yourself, or use the reduce() method which you will find examples of in the package documentation.
Show us what you have tried and tell us how it is going. This is one of the circumstances where it is much easier to use an IDE than the command line.
I was thinking about something like this, however I couldn't put it in code