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

fae0ux8s  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(166)

从一个包含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个流似乎矫枉过正。我如何使这更有效率?

uxhixvfz

uxhixvfz1#

等效的一行程序:

Double totalTaxRate = itemList.stream()
                .filter(i -> i.getItemClass() != 200)
                .flatMap(i -> i.getTaxes().stream())
                .mapToDouble(t -> t.getTaxRate()).sum();

相关问题