从一个包含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个流似乎矫枉过正。我如何使这更有效率?
1条答案
按热度按时间uxhixvfz1#
等效的一行程序: