Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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<>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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());
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading