为了账号安全,请及时绑定邮箱和手机立即绑定

使用流优化列表遍历

使用流优化列表遍历

繁花如伊 2023-02-23 17:41:19
我有一个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();}
查看完整描述

2 回答

?
九州编程

TA贡献1785条经验 获得超4个赞

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


查看完整回答
反对 回复 2023-02-23
?
饮歌长啸

TA贡献1951条经验 获得超3个赞

代码中的注释可能有点难以理解,但这就是我的全部时间。


// 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) {

    // Stream over all the batches...

    return batches.stream()


    // Group them by 'batch number' (gives a Map<String, List<BatchDTO>>)

            .collect(Collectors.groupingBy(BatchDTO::getBatchNumber))


    // Stream over all the entries in that Map (gives Stream<Map.Entry<String, List<BatchDTO>>>)

            .entrySet().stream()


    // Build a map from the Stream of entries

    // Keys stay the same

            .collect(Collectors.toMap(Entry::getKey, 


    // Values are now the result of streaming the List<BatchDTO> and summing 'getQuantity'

                    entry -> entry.getValue().stream().mapToDouble(BatchDTO::getQuantity).sum()));

}

注意:我不保证这比您现有的方法更优化......但它可以使用 Streams 完成工作。quantity注意:如果是null针对您的任何一个,这将引发异常BatchDTO...


查看完整回答
反对 回复 2023-02-23
  • 2 回答
  • 0 关注
  • 92 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号