java流:获取嵌套对象列表中的字段总和

问题描述 投票:0回答:1

从包含 List 的 List 中,根据 Item 类中的字段过滤 List 后如何获取 Tax 类中特定字段的总和?

这就是我到目前为止所做的 -

public class Item {
    private long itemClass;
    private List<Tax> taxList;

    public long getItemClass() {
        return itemClass;
    }
    public void setItemClass(long itemClass) {
        this.itemClass = itemClass;
    }
    public List<Tax> getTaxes() {
        return taxList;
    }
    public void setTaxList(List<Tax> taxList) {
        this.taxList = taxList;
    }

}


public class Tax {
    private double taxRate;

    public double getTaxRate() {
        return taxRate;
    }
    public void setTaxRate(double taxRate) {
        this.taxRate = taxRate;
    }
}


public class App {
    public static void main(String[] args) {
        Item item1 = new Item();
        item1.setItemClass(100);

        Item item2 = new Item();
        item1.setItemClass(200);

        Item item3 = new Item();
        item1.setItemClass(300);

        Tax tax1 = new Tax();
        tax1.setTaxRate(0.01);

        Tax tax2 = new Tax();
        tax1.setTaxRate(0.02);

        Tax tax3 = new Tax();
        tax1.setTaxRate(0.03);

        item1.setTaxList(Arrays.asList(tax1, tax2));
        item2.setTaxList(Arrays.asList(tax1, tax3));
        item3.setTaxList(Arrays.asList(tax1, tax2, tax3));

        List<Item> itemList = Arrays.asList(item1, item2, item3);

        List<Item> filteredItemList = itemList.stream().filter(i -> i.getItemClass() != 200).collect(Collectors.toList());
        List<Tax> filteredTaxList = filteredItemList.stream().map(i -> i.getTaxes()).flatMap(t -> t.stream()).collect(Collectors.toList());
        Double totalTaxRate = filteredTaxList.stream().mapToDouble(t -> t.getTaxRate()).sum();

        System.out.println(totalTaxRate); //expected result 0.09
    }
}

我能够得到想要的结果。但 3 个流似乎有点过分了。我该如何提高效率?

java java-stream
1个回答
2
投票

等效的一句:

Double totalTaxRate = itemList.stream()
                .filter(i -> i.getItemClass() != 200)
                .flatMap(i -> i.getTaxes().stream())
                .mapToDouble(t -> t.getTaxRate()).sum();
© www.soinside.com 2019 - 2024. All rights reserved.