Skip to content
Advertisement

Java 8 Streams Map Reduced Value after Group By

Using Java streams, I would like to calculate the cost given a list of items, grouped by type. After getting the cost, I would like to map the BigDecimal to a formatted currency String. Is it possible to map reduced and grouped values?

JavaScript

Advertisement

Answer

You can wrap your reducing collector in CollectingAndThen collector which takes a downstream collector and a finisher function. CollectingAndThen is a special collector that allows us to perform another action on a result straight after collecting ends. Change your map type to Map<String, String> and do :

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement