You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历Set集合累加事件总时长?当前代码仅获取最后一个事件时长

问题:如何累加Set集合中所有Event的时长?

我需要遍历一个Set<Event>集合,获取每个事件的开始与结束时间,计算单个事件的时长后将所有时长累加得到总时长。但当前使用的代码仅能获取最后一个事件的时长,无法实现累加,不确定循环逻辑是否正确。代码如下:

Set<Event> events = eventService.findByUsers(user);
Long duration = null;
for(Event event : events) {
    LocalTime startTime = event.getStart().toLocalTime();
    LocalTime endTime = event.getEnd().toLocalTime();
    duration = Duration.between(startTime, endTime).toHours();
    System.out.println("The time between shifts is " + duration);
    Long totalTime = duration += duration;
}

问题分析

你的代码有两个核心问题导致无法正确累加:

  1. 变量作用域与初始化错误:totalTime定义在循环内部,每次循环都会重新创建这个变量,根本无法保存累加后的总时长;同时duration初始化为null,第一次赋值前使用会有风险,且每次循环都会被覆盖为当前事件的时长,没有保留之前的累加结果。
  2. 累加逻辑错误:duration += duration相当于把当前事件的时长翻倍,而不是将当前时长加到总时长里,这完全不符合累加的需求。

修正后的代码

Set<Event> events = eventService.findByUsers(user);
// 初始化总时长为0,避免null的风险
Long totalDuration = 0L;

for(Event event : events) {
    LocalTime startTime = event.getStart().toLocalTime();
    LocalTime endTime = event.getEnd().toLocalTime();
    // 计算当前事件的时长
    Long currentDuration = Duration.between(startTime, endTime).toHours();
    System.out.println("The time between shifts is " + currentDuration);
    // 将当前时长累加到总时长中
    totalDuration += currentDuration;
}

// 循环结束后输出总时长
System.out.println("Total event duration: " + totalDuration + " hours");

关键改动说明

  • 把总时长变量totalDuration定义在循环外部,确保它能在整个循环过程中保存累加结果
  • 初始化总时长为0L(长整型的0),避免null引发的空指针异常
  • 用currentDuration存储单个事件的时长,避免覆盖总时长变量
  • 使用totalDuration += currentDuration实现正确的累加逻辑,每次把当前事件的时长加到总时长里

内容的提问来源于stack exchange,提问作者Jane Ryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:25:37