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...
添加回答
舉報