使用流优化列表遍历

我有一个List<BatchDTO>与以下类


public class BatchDTO {


    private String batchNumber;

    private Double quantity;

.

.

//Getters and setters

}

如果 batchNumber 重复,我要做的是总结总数。我使用 LinkedHashMap 来实现它,并进行了迭代。但我想要的是一种更优化的方式。我可以使用流以优化的方式执行此操作吗?


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

}


繁花如伊
浏览 93回答 2
2回答

九州编程

假设BatchDTO拥有所有 args 构造函数,您可以从返回Map到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()

饮歌长啸

代码中的注释可能有点难以理解,但这就是我的全部时间。// Result will be a Map where the keys are the unique 'batchNumber's, and the// values are the sum of the 'quantities' for those with that 'batchNumber'.public Map<String, Double> countBatchQuantities(final List<BatchDTO> batches) {&nbsp; &nbsp; // Stream over all the batches...&nbsp; &nbsp; return batches.stream()&nbsp; &nbsp; // Group them by 'batch number' (gives a Map<String, List<BatchDTO>>)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.groupingBy(BatchDTO::getBatchNumber))&nbsp; &nbsp; // Stream over all the entries in that Map (gives Stream<Map.Entry<String, List<BatchDTO>>>)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .entrySet().stream()&nbsp; &nbsp; // Build a map from the Stream of entries&nbsp; &nbsp; // Keys stay the same&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(Entry::getKey,&nbsp;&nbsp; &nbsp; // Values are now the result of streaming the List<BatchDTO> and summing 'getQuantity'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; entry -> entry.getValue().stream().mapToDouble(BatchDTO::getQuantity).sum()));}注意:我不保证这比您现有的方法更优化......但它可以使用 Streams 完成工作。quantity注意:如果是null针对您的任何一个,这将引发异常BatchDTO...
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java