Search code examples
javafunctional-programminghashmapjava-streamlinkedhashmap

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


This is my map Map<LocalDate,List<Integer>> map = new LinkedHashMap<>();

Question 1: How to compute the sum for each list in Map<>

Output of the 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]

My try

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

Desired Output (Calculate and display the sum for each list)

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

Solution

  • You could try this

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