Java Stream: Group and Sum StatisticsResultDTO Objects by Multiple Fields
To group the 'StatisticsResultDTO' objects by 'empName', 'empCode', and 'deptName' and calculate the sum of 'calculationResultValue' for each group using a stream, you can use the following code:
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class StatisticsResultDTO {
// ... existing code ...
public static void main(String[] args) {
// Create a sample list of StatisticsResultDTO objects
List<StatisticsResultDTO> resultList = new ArrayList<>();
// Add your StatisticsResultDTO objects to the list
// Group the objects by empName, empCode, and deptName
Map<String, Map<String, List<StatisticsResultDTO>>> groupedMap = resultList.stream()
.collect(Collectors.groupingBy(dto -> dto.getEmpName() + "-" + dto.getEmpCode() + "-" + dto.getDeptName(),
Collectors.groupingBy(StatisticsResultDTO::getEvaluationDimension)));
// Calculate the sum of calculationResultValue for each group
Map<String, Map<String, BigDecimal>> integrityTotalMap = new HashMap<>();
for (Map.Entry<String, Map<String, List<StatisticsResultDTO>>> entry : groupedMap.entrySet()) {
String key = entry.getKey();
Map<String, List<StatisticsResultDTO>> innerMap = entry.getValue();
Map<String, BigDecimal> sumMap = new HashMap<>();
for (Map.Entry<String, List<StatisticsResultDTO>> innerEntry : innerMap.entrySet()) {
String evaluationDimension = innerEntry.getKey();
List<StatisticsResultDTO> dtoList = innerEntry.getValue();
BigDecimal sum = dtoList.stream()
.map(StatisticsResultDTO::getCalculationResultValue)
.reduce(BigDecimal.ZERO, BigDecimal::add);
sumMap.put(evaluationDimension, sum);
}
integrityTotalMap.put(key, sumMap);
}
// Print the integrityTotalMap
integrityTotalMap.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
This code will group the 'StatisticsResultDTO' objects by 'empName', 'empCode', and 'deptName', and then calculate the sum of 'calculationResultValue' for each group. The result will be stored in the 'integrityTotalMap' map, where the key is the group key ('empName-empCode-deptName') and the value is another map where the key is the 'evaluationDimension' and the value is the sum of 'calculationResultValue' for that dimension.
原文地址: https://www.cveoy.top/t/topic/lPBy 著作权归作者所有。请勿转载和采集!