首页 > 解决方案 > 获取地图中值的总和

问题描述

在对每个值应用操作后,我必须得到地图中值的总和。

我已经这样做了:

   Map<Employee, Integer> employeeBudget = committedHoursPerDay.entrySet()
            .stream()
            .collect(Collectors.toMap(Map.Entry::getKey, o -> o.getKey().getHourlyWage() * o.getValue()));

    //Get the total cost for all the employee
    int manpowerBudget = employeeBudget.values()
            .stream()
            .mapToInt(Integer::intValue)
            .sum();

此解决方案有效。我认为有更好的方法来解决这个问题,但我无法弄清楚。

标签: javajava-stream

解决方案


事实上,我认为你可以只用一个流来做到这一点:

int manpowerBudget = committedHoursPerDay.entrySet().stream()
                .mapToInt(kv-> kv.getKey().getHourlyWage() * kv.getValue())
                .sum();


推荐阅读