I have a list of products with the amount of one of the attributes. And the list may contain the common name of the product, and other attributes are different. Therefore, I want to group the list by product and the sum of the sum of products that have a common name in java 8 using grouping and summation.
Example:
[
{
"name":"Product A",
"amount":"40.00",
"description":"Info1",
"number":"65"
},
{
"name":"Product A",
"amount":"50.00",
"description":"Info2",
"number":"67"
},
{
"name":"Product A",
"amount":"100.00",
"description":"Info3",
"number":"87"
},
{
"name":"Product B",
"amount":"45.00",
"description":"Info4",
"number":"86"
},
{
"name":"Product D",
"amount":"459.00",
"description":"Info5",
"number":"7"
},
{
"name":"Product B",
"amount":"50.00",
"description":"Info6",
"number":"8"
}
]
The output should be similar to this:
{
"Product A = 190.00":[
{
"name":"Product A",
"amount":"40.00",
"description":"Info1",
"number":"65"
},
{
"name":"Product A",
"amount":"50.00",
"description":"Info2",
"number":"67"
},
{
"name":"Product A",
"amount":"100.00",
"description":"Info3",
"number":"87"
}
],
"Product B=95.00":[
{
"name":"Product B",
"amount":"45.00",
"description":"Info4",
"number":"86"
},
{
"name":"Product B",
"amount":"50.00",
"description":"Info6",
"number":"8"
}
],
"Product D = 459.00":[
{
"name":"Product D",
"amount":"459.00",
"description":"Info5",
"number":"7"
}
]
I created a bean class ProductBeanthat has all the fields (name, quantity, description and number), as well as recipients and setters for the same. And productBeans has a list of all products.
Map<String, List<ProductBean>> groupByProduct =
productBeans.stream()
.collect(Collectors.groupingBy(item -> item.getName()))
Map<String, BigDecimal> result =
productBeans.stream()
.collect(Collectors.groupingBy(ProductBean::getName,
Collectors.mapping(ProductBean::getAmount,
Collectors.reducing(BigDecimal.ZERO, BigDecimal::add))));
groupByProduct has a list of products grouped by name. the result gives a product map as a key and the total amount of this product as a value.
. , , . .
, , , .