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

如何计算Map<LocalDate,List<Integer>>中每个列表的总和并关联对应日期

你当前的实现仅遍历了Map的values集合,处理过程中丢失了对应的LocalDate键信息,直接遍历Map的entrySet()即可同时保留键和处理对应的值。

实现代码

方案1:收集为新的Map<LocalDate, Integer>保留映射关系

如果需要后续继续使用日期和总和的映射关系,可以用如下方式收集为新Map,同时保留原LinkedHashMap的插入顺序:

import java.util.LinkedHashMap;
import java.util.Map;
import java.time.LocalDate;
import java.util.stream.Collectors;

Map<LocalDate,List<Integer>> map = new LinkedHashMap<>();
// 这里是你原有给Map赋值的逻辑

Map<LocalDate, Integer> dateSumMap = map.entrySet()
        .stream()
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                entry -> entry.getValue().stream().mapToInt(Integer::intValue).sum(),
                // 无键冲突时合并函数可随意指定,此处作用为指定目标Map为LinkedHashMap保留插入顺序
                (oldVal, newVal) -> oldVal,
                LinkedHashMap::new
        ));

方案2:直接输出期望格式

如果不需要存储映射关系,只需要打印结果,可直接遍历输出:

map.entrySet().forEach(entry -> {
    int sum = entry.getValue().stream().mapToInt(Integer::intValue).sum();
    System.out.printf("%s [%d]%n", entry.getKey(), sum);
});

运行后输出结果和你给出的期望效果完全一致。

内容的提问来源于stack exchange,提问作者mike kong

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 21:45:00