按变量分组列表并计算对象变量的总和

Grouping list by variables and counting sums of object variables

我必须使用流对给定列表中的元素进行分组。我想将它们放入地图中(按变量分组 'vat' ), 然后计算每个键中每个对象变量的总和。

我被困在求和流中了。我做了分组流但是现在,经过几个小时的编码我仍然不知道该怎么做。

函数代码:

    public static List<Product> calculatingTaxes(List<Product> products){
        Map<Double, List<Product>> productTaxesMap = new HashMap<>();

        productTaxesMap = products.stream()
                .collect(Collectors.groupingBy(Product::getVat));

        System.out.println(productTaxesMap);
        return null;
    }

sout函数就是看函数在做什么,当前输出

{1.0=[Product{netPrice=100.0, vat=1.0, vatAmount=0.0, grossPrice=100.0}, 
Product{netPrice=100.0, vat=1.0, vatAmount=0.0, grossPrice=100.0}], 1.23= 
[Product{netPrice=100.0, vat=1.23, vatAmount=23.0, grossPrice=123.0}, 
Product{netPrice=100.0, vat=1.23, vatAmount=23.0, grossPrice=123.0}, 
Product{netPrice=100.0, vat=1.23, vatAmount=23.0, grossPrice=123.0}], 1.08= 
[Product{netPrice=100.0, vat=1.08, vatAmount=8.0, grossPrice=108.0}, 
Product{netPrice=100.0, vat=1.08, vatAmount=8.0, grossPrice=108.0}]}

产品代码 class:

public class Product {
private double netPrice;
private double vat;
private double vatAmount;
private double grossPrice;

public Product(double netPrice, double vat) {

    this.netPrice = netPrice;
    this.vat = vat;
    this.grossPrice = netPrice * vat;
    this.vatAmount = grossPrice - netPrice;
}

public double getNetPrice() {
    return netPrice;
}

public double getVatAmount() {
    return vatAmount;
}

public double getGrossPrice() {
    return grossPrice;
}

public double getVat() {
    return vat;
}

@Override
public String toString() {
    return "Product{" +
            "netPrice=" + netPrice +
            ", vat=" + vat +
            ", vatAmount=" + vatAmount +
            ", grossPrice=" + grossPrice +
            '}';
}

我想要上层函数,return netPrice、grossPrice 和 vat 金额的总和到每个 vat key(0-8-23%)。 我尝试使用 Collectors.grouppingBy() 收集和求和元素。通过过滤等,但 none 有效。

假设您的输入是:

List<Product> products = Arrays.asList(
        new Product(100.0, 1.0),
        new Product(100.0, 1.0),
        new Product(100.0, 1.23),
        new Product(100.0, 1.23),
        new Product(100.0, 1.23),
        new Product(100.0, 1.08),
        new Product(100.0, 1.08)
);

你可以这样做:

Map<Double, Product> vatToReducedProduct = products.stream()
        .collect(Collectors.toMap(Product::getVat,
                Function.identity(),
                (p1, p2) -> new Product(p1.getNetPrice() + p2.getNetPrice(), p1.getVat())));

输出:

{
 1.0=Product{netPrice=200.0, vat=1.0, vatAmount=0.0, grossPrice=200.0}, 
 1.23=Product{netPrice=300.0, vat=1.23, vatAmount=69.0, grossPrice=369.0}, 
 1.08=Product{netPrice=200.0, vat=1.08, vatAmount=16.0, grossPrice=216.0}
}