如何计算 Map<> 中每个列表的总和?

How to compute sum for each list in Map<>?

这是我的地图Map<LocalDate,List<Integer>> map = new LinkedHashMap<>();

问题 1:如何计算 Map<>中每个列表的总和

地图输出<>

2020-01-22 [0, 0, 7, 0, 0, 0, 0, 0, 3, 8, 0, 4,0]
2020-01-23 [0, 0, 7, 0, 0, 0, 0, 0, 3, 0, 0, 4,0] 
2020-01-24 [0, 0, 7, 0, 0, 0, 0, 0, 3, 0, 0, 5,0]
2020-01-25 [0, 0, 8, 0, 0, 0, 0, 0, 3, 0, 0, 4,0]
2020-01-26 [0, 0, 7, 0, 0, 0, 0, 0, 3, 0, 0, 8,0]
2020-01-27 [0, 0, 9, 0, 0, 0, 0, 0, 3, 0, 0, 4,0]

我的尝试

Map<LocalDate,List<Integer>> map = new LinkedHashMap<>();
 List<Integer> integerList =map
                .values()
                .stream()
                .map(l->{
                    int sum = l
                            .stream()
                            .mapToInt(Integer::intValue)
                            .sum();
                    return sum;
                }).collect(Collectors.toList());

The code here that I have tried, I can only form the new list and calculate it. But I would like the date and its sum of num display at the same time

期望输出(计算并显示每个列表的总和)

2020-01-22 [22]
2020-01-23 [14] 
2020-01-24 [15]
2020-01-25 [14]
2020-01-26 [18]
2020-01-27 [16]

你可以试试这个

Map<LocalDate,Integer> result = new LinkedHashMap<>();
map.forEach((key, value) -> {
 result.put(key,value.stream().mapToInt(Integer::intValue).sum());
});

toMap 是一个很好的候选人:

public static void main(String[] args) {
    Map<LocalDate,List<Integer>> map = new LinkedHashMap<>();

    map.put(LocalDate.of(2020,01,22), List.of(0, 0, 7, 0, 0, 0, 0, 0, 3, 8, 0, 4,0));
    map.put(LocalDate.of(2020,01,23), List.of(0, 0, 7, 0, 0, 0, 0, 0, 3, 0, 0, 4,0));
    map.put(LocalDate.of(2020,01,24), List.of(0, 0, 7, 0, 0, 0, 0, 0, 3, 0, 0, 5,0));
    map.put(LocalDate.of(2020,01,25), List.of(0, 0, 8, 0, 0, 0, 0, 0, 3, 0, 0, 4,0));
    map.put(LocalDate.of(2020,01,26), List.of(0, 0, 7, 0, 0, 0, 0, 0, 3, 0, 0, 8,0));
    map.put(LocalDate.of(2020,01,27), List.of(0, 0, 9, 0, 0, 0, 0, 0, 3, 0, 0, 4,0));

    var output = map.entrySet().stream()
                  .collect(toMap(Map.Entry::getKey,
                                 e -> e.getValue().stream().reduce(0, Integer::sum)));

    System.out.println(output);
}

其中一个超载 toMap 需要一个 keyMapper - 这里是原始地图中的键 和一个 valueMapper - 在这里,我们通过对列表中的数字求和来映射(获取)值。

以上代码的输出可能如下所示:

{2020-01-27=16, 2020-01-26=18, 2020-01-25=15, 2020-01-24=15, 2020-01-23=14, 2020-01-22=22}

您可以使用重载的 toMap 来指示使用 LinkedHashMap:

var output = map.entrySet().stream()
               .collect(toMap(
                  Map.Entry::getKey, 
                  e -> e.getValue().stream().reduce(0, Integer::sum), 
                  // Conflict resolving function: If the same key is seen again, 
                  // use the latest value. 
                  (oldValue, newValue) -> newValue, 
                  LinkedHashMap::new));

System.out.println(output);

以上代码的输出是:

{2020-01-22=22, 2020-01-23=14, 2020-01-24=15, 2020-01-25=15, 2020-01-26=18, 2020-01-27=16}