使用startDate和endDate按月份分组

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

我有一个包含]的类模块>

private LocalDate startDate;        
private LocalDate endDate;       
private Map<Teacher, Integer> workedHoursPerDay;

每个老师都有一个属性

private int hourlyWage;   

请求是获取按月分组的所有教师的每月预算。预期的回报是Map。我进行了搜索,但不知道如何使用startDate和endDate进行操作。

[单个模块的每月支出是指该月中所有工作日内分配给该模块的所有教师的累计费用。

逻辑将是:-从所有模块(设置)中获取教该模块的老师和小时数(Map workingHoursPerDay)。然后将每个老师的工作时间乘以小时工资。最后,使用每个模块的startDate和endDate按月对成本进行分组。

我已经做了类似的事情,但没有得到预期的结果

公共地图calculateCumulativeMonthlySpends(){

    //Get the min startDate of all the  modules
    LocalDate localDateStart = modules.stream()
            .flatMap(modules -> module.getWorkingDays().stream())
            .min(LocalDate::compareTo).get();
    //Get the max endDate of all the modules
    LocalDate localDateEnd = modules.stream()
            .flatMap(module -> module.getWorkingDays().stream())
            .max(LocalDate::compareTo).get();

    //Iterate from the start date to the end date, calculate the daily cost for all the module
    //and sum the cost of all the days for the all modules
    //Then create a map with moth as a key and the cost of all the modules for each month
    //Finally sort the map by key

    return Stream.iterate(localDateStart, d -> d.plusDays(1))
            .limit(ChronoUnit.DAYS.between(localDateStart, localDateEnd) + 1)
            .collect(Collectors.toMap(LocalDate::getMonth, day -> dailyCost(day, modules), Integer::sum))
            .entrySet()
            .stream()
            .sorted(Map.Entry.comparingByKey())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                    (oldValue, newValue) -> oldValue, LinkedHashMap::new));
}

/**
 * Calculate the daily cost for all the modules
 * Check if the modules's working days contain the attribute day
 * If yes sum(),  add the daily cost of this module to the other modules' daily cost
 *
 * @param day
 * @param modules
 * @return
 */
private Integer dailyCost(LocalDate day, Set<Module> modules) {

    return modules.stream()
            .filter(module -> module.getWorkingDays().contains(day))
            .flatMap(p -> p.getCommittedHoursPerDay().entrySet().stream())
            .mapToInt(e -> e.getKey().getHourlyWage() * e.getValue())
            .sum();
}

代码已修改。我现在有预期的结果,但我希望有一个更好的方法。

预计:{JANUARY = 19529、2月= 26909、3月= 35593、4月= 60243、5月= 79172、6月= 70135、7月= 72470、8月= 40161、9月= 21750、10月= 8636,NOVEMBER = 1344}

我有一个包含私有LocalDate startDate的类Module;私有LocalDate endDate;私人地图workHoursPerDay;每个老师都有一个属性...

java java-stream grouping
2个回答
0
投票

如果没有很多信息,很难在代码中找到错误。但是它可能会对您自己解释如何找到它更有帮助。

您在dailyCost中的单个表达式太复杂而无法调试。 Java流是很棒的,但是它们有一个很大的问题:使用交互式调试器很难调试它们(请参阅Problems using interactive debuggers with Java 8 streams,不幸的是它没有有用的答案)。


0
投票

经过调查,我知道了。工作日包括周末,这是错误的。

© www.soinside.com 2019 - 2024. All rights reserved.