如果我有一个对象列表,例如产品,这些产品将按产品类型分组。我需要汇总的价格和数量。
{{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}}
我需要一个看起来像这样的结果列表
{{type:normal,price:26,quantity:7},{type:luxury,price:356,quantity:3}}
有没有办法使用Java流来实现这一目标?
答案 0 :(得分:1)
怎么样,
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()))));
其中Product
类应该看起来像这样。
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;
}
// ...
}