Java Stream: Convert String Quantity to BigDecimal and Calculate Sum for G Units in List<OdsMaterialDocumentItem>
This code snippet demonstrates how to use Java streams to convert a list of OdsMaterialDocumentItem objects with String QuantityInEntryUnit to BigDecimal and calculate the sum for entries with EntryUnit 'G' (grams) converted to KG (kilograms).
List<OdsMaterialDocumentItem> odsMaterialDocumentItems261 = odsMaterialDocumentMapper.selectItemsByMap(map);
List<BigDecimal> quantityInKgList = odsMaterialDocumentItems261.stream()
.filter(item -> item.getEntryUnit().equals('G'))
.map(item -> new BigDecimal(item.getQuantityInEntryUnit()).divide(new BigDecimal(1000)))
.collect(Collectors.toList());
BigDecimal sum = quantityInKgList.stream()
.reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println('Sum of QuantityInEntryUnit converted to KG: ' + sum);
Explanation:
- Filtering: The
filteroperation selects only items where theEntryUnitis 'G'. - Mapping: The
mapoperation converts theQuantityInEntryUnit(a String) to aBigDecimaland then divides by 1000 to convert grams to kilograms. - Collecting: The
collect(Collectors.toList())operation gathers the convertedBigDecimalvalues into a new list. - Reducing: The
reduceoperation iterates through thequantityInKgListand uses theBigDecimal::addmethod to sum up the values. - Printing: The
System.out.printlnstatement prints the sum of theQuantityInEntryUnitconverted to KG.
This code snippet provides a concise and efficient way to process and calculate data from a list of objects using Java streams.
原文地址: https://www.cveoy.top/t/topic/ohLb 著作权归作者所有。请勿转载和采集!