如何用流API Java重写两个循环



结构:

Accounting
+ Map<Employee, EmployeeCard> getEmployeeCards()
EmployeeCard
+ Map<LocalDate, Report> getReports()
Report
+ double getSalary()

我需要计算所有员工卡的所有报告的工资总额。

我的变体使用两个循环:

public double getCostsOfEmployeesSalaries() {
double sumOfSalary = 0;
for (EmployeeCard card : accounting.getEmployeeCards().values()) {
Collection<Report> reports = card.getReports().values();
for (Report report : reports) {
sumOfSalary += report.getSalary();
}
}
return sumOfSalary;
}

是否有使用java流API计算和的解决方案?

试试这样的东西:

public double getCostsOfEmployeesSalaries() {
return accounting.getEmployeeCards().values().stream()
.map(card -> card.getReports().values())
.flatMap(Collection::stream)
.mapToDouble(Report::getSalary)
.sum();
}

你可以这样做:

public double getCostsOfEmployeesSalaries() {
return accounting.getEmployeeCards().values()
.stream()
.mapToDouble(card -> card.getReports().values()
.stream()
.mapToDouble(Report::getSalary)
.sum())
.sum();
}

通过对每个报告中的工资求和,将每张卡映射到一个双数据流,然后对所得的双数据流求和。正如评论中所指出的,在处理货币时不应该使用double,而应该使用BigDecimal。

就我个人而言,我会使用循环而不是流,但这只是我的偏好。

最新更新