Optimizing the list traversal with stream

arjuncc :

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();
}
Ruslan :

You could try using stream api the way @Naman suggested in comments. And assuming BatchDTO has all args constructor you could return back from Map to List<BatchDTO>

List<BatchDTO> collect = list.stream()
        .collect(groupingBy(BatchDTO::getBatchNumber, summingDouble(BatchDTO::getQuantity)))
        .entrySet().stream()
        .map(entry -> new BatchDTO(entry.getKey(), entry.getValue()))
        .collect(Collectors.toList());

JavaDoc: groupingBy(), summingDouble()

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=122695&siteId=1