使用流优化列表遍历

时间:2019-06-28 13:33:55

标签: java list java-8 java-stream

我有一个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 个答案:

答案 0 :(得分:3)

您可以尝试以流@Naman在注释中建议的方式使用流api。假设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()

答案 1 :(得分:2)

代码中的注释可能有点不可读,但这是我所有的时间。

// 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的{​​{1}}是null,这将引发异常。