【问题标题】:Java streams grouping a column and fetching multiple aggregated valuesJava 流对列进行分组并获取多个聚合值
【发布时间】:2018-09-24 12:56:30
【问题描述】:

如果我有一个对象列表,例如产品,则将按产品类型分组。我需要汇总的价格和数量。

{{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 流来实现这一点??

【问题讨论】:

  • 我需要按一列分组。那么我应该在reduce中将name设置为空字符串并保持与list相同类型的对象吗?如果是这样,怎么办?
  • 如何为此证明正确的 java 类?
  • @Eugene 查看我对您的链接答案的评论...
  • 你有地图列表吗?产品清单?字符串列表?请澄清。

标签: list maps java-stream


【解决方案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;
    }
    // ...
}

【讨论】:

  • 适用于我的情况。非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 2018-06-08
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多