2 回答

TA贡献1785条经验 获得超4个赞
假设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()

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...
添加回答
举报