I have a List<BatchDTO> with the following class
public class BatchDTO {
private String batchNumber;
private Double quantity;
.
.
//Getters and setters
}
What I have to do is to sum up the total if the batchNumber is duplicate. I have used a LinkedHashMap to implement this, and did the iterations. But what I would like to have is a more optimized way. Can I use stream to do this in an optimized way.
private static List<BatchDTO > getBatchDTO (Map<String, BatchDTO > batchmap) {
return batchmap.values().stream().collect(Collectors.toList());
}
private static Map<String, BatchDTO > getBatchMap(List<BatchDTO > batchList, Map<String, BatchDTO > batchMap) {
for (BatchDTO batchDTO : batchList) {
batchMap = getBatchMap(batchMap, batchDTO );
}
return batchMap;
}
private static Map<String, BatchDTO > getBatchMap(Map<String, BatchDTO > batchMap, BatchDTO batchObject) {
String batchCode = batchObject.getBatchNumber();
if(!batchMap.containsKey(batchCode)) {
batchMap.put(batchCode, batchObject);
} else {
batchObject.setQuantity(getTotalQuantity(batchMap,batchObject));
batchMap.put(batchCode, batchObject);
}
return batchMap;
}
private static Double getTotalQuantity(Map<String, BatchDTO > batchmap, BatchDTO batchObject) {
return batchmap.get(batchObject.getBatchNumber()).getQuantity() + batchObject.getQuantity();
}