Map Stream to List of Objects With Total

Viewed 218

I have a Map that I got from this code

Map<String, Long> countsMap = sampleObjectList.stream()
        .collect(Collectors.groupingBy(sampleObject::getStatus, Collectors.counting()));

after getting the map, I need to create a list of objects with the count of each status and the total count.

The normal way I do this using a for loop below.

List<ObjectCountDTO> dtoList = new ArrayList<>();
long allCount = 0L;
for(Map.Entry<String, Long> entry : countsMap.entrySet()) {
    long count = entry.getValue();
    allCount += count;
    dtoList.add(new ObjectCountDTO(entry.getKey(), count)); 
}
dtoList.add(new ObjectCountDTO("ALL", allCount));

Is there any way to do this in java 8 using streams?

2 Answers

You can stream the entrySet of the frequency Map.

List<ObjectCountDTO> dtoList = countsMap.entrySet().stream()
 .map(e -> new ObjectCountDTO(e.getKey(), e.getValue()).collect(Collectors.toList());
dtoList.add(new ObjectCountDTO("ALL", 
       countsMap.values().stream().mapToLong(i->i).sum()));

If you want to do everything in a single stream, you can use below code snippet

List<ObjectCountDTO> dtoList = new ArrayList<>();
dtoList.add(new ObjectCountDTO("ALL", countsMap.entrySet().stream()
        .map(e -> {
            dtoList.add(new ObjectCountDTO(e.getKey(), e.getValue()));
            return e;
        })
        .map(e -> e.getValue())
        .reduce(0L, (a, b) -> a + b)));
Related