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:

  1. Filtering: The filter operation selects only items where the EntryUnit is 'G'.
  2. Mapping: The map operation converts the QuantityInEntryUnit (a String) to a BigDecimal and then divides by 1000 to convert grams to kilograms.
  3. Collecting: The collect(Collectors.toList()) operation gathers the converted BigDecimal values into a new list.
  4. Reducing: The reduce operation iterates through the quantityInKgList and uses the BigDecimal::add method to sum up the values.
  5. Printing: The System.out.println statement prints the sum of the QuantityInEntryUnit converted to KG.

This code snippet provides a concise and efficient way to process and calculate data from a list of objects using Java streams.

Java Stream: Convert String Quantity to BigDecimal and Calculate Sum for G Units in List<OdsMaterialDocumentItem>

原文地址: https://www.cveoy.top/t/topic/ohLb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录