将流映射到具有总计的对象列表

Map Stream to List of Objects With Total

我有一个 Map 是我从这段代码中得到的

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

获取地图后,我需要创建一个对象列表,其中包含每个状态的计数和总计数。

我使用下面的 for 循环执行此操作的正常方法。

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

在 java 8 中使用流有什么方法可以做到这一点吗?

您可以stream频率MapentrySet

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()));

如果你想在一个流中做所有事情,你可以使用下面的代码片段

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