0

If I have a list of object say products, that are to be grouped by product type. And I need the aggregated price and quantity.

{{name:a1,type:normal,price:23,quantity:4}, 
{name:a2,type:normal,price:3,quantity:3},
{name:a3,type:luxury,price:233,quantity:1},
{name:a4,type:luxury,price:123,quantity:2}}

I need a resultant list which looks like this

{{type:normal,price:26,quantity:7},{type:luxury,price:356,quantity:3}}

Is there a way to achieve this using java streams??

HareshKannan
  • 83
  • 11

1 Answers1

1

How about this,

Map<String, Product> result = products.stream()
    .collect(Collectors.groupingBy(Product::getType,
        Collectors.reducing(new Product(null, null, 0, 0), (p1, p2) -> new Product(null, p1.getType(),
            p1.getPrice() + p2.getPrice(), p1.getQuantity() + p2.getQuantity()))));

where Product class should look something like this.

public class Product {
    private String name;
    private String type;
    private double price;
    private int quantity;

    public Product(String name, String type, double price, int quantity) {
        super();
        this.name = name;
        this.type = type;
        this.price = price;
        this.quantity = quantity;
    }
    // ...
}
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63