List<RelayLinkReportResultVo> relayLinkReportResultVos 求和某个字段值,是String类型的金额
时间: 2024-03-10 07:44:18 浏览: 17
好的,您可以使用以下的代码来实现对 List<RelayLinkReportResultVo> 中某个字段值求和:
```java
double sum = relayLinkReportResultVos.stream()
.mapToDouble(vo -> Double.parseDouble(vo.getAmount()))
.sum();
```
其中,`getAmount()` 方法返回的是 `String` 类型的金额,我们将它转换为 `double` 类型后再进行求和。
相关问题
List<RelayLinkReportResultVo> relayLinkReportResultVos 求和某个字段值,是String类型的BigDecimal金额
好的,如果金额是 `String` 类型的 `BigDecimal`,您可以使用以下代码来实现对 `List<RelayLinkReportResultVo>` 中某个字段值求和:
```java
BigDecimal sum = relayLinkReportResultVos.stream()
.map(RelayLinkReportResultVo::getAmount)
.map(BigDecimal::new)
.reduce(BigDecimal.ZERO, BigDecimal::add);
```
其中 `getAmount()` 方法返回的是 `String` 类型的 `BigDecimal`,我们使用 `BigDecimal` 的构造方法将其转换为 `BigDecimal` 类型,最后使用 `reduce` 方法对所有金额进行求和。
Map<String, List<CoreSpaceExcelBo>> map 根据 CoreSpaceExcelBo对象的CartonCode字段去重,累加CoreSpaceExcelBo中的num字段
首先,需要使用Java的Stream API对List进行处理,将其中的重复元素去掉,并累加重复元素的num字段。可以使用groupingBy方法根据CartonCode字段进行分组,然后使用mapping方法将每个组中的CoreSpaceExcelBo对象转换为其num字段的值,最后使用summingInt方法对这些值进行求和。代码如下:
```
Map<String, List<CoreSpaceExcelBo>> map = new HashMap<>();
map = map.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey,
entry -> entry.getValue().stream().collect(
Collectors.groupingBy(CoreSpaceExcelBo::getCartonCode,
Collectors.mapping(CoreSpaceExcelBo::getNum, Collectors.summingInt(Integer::intValue))))
.entrySet().stream()
.map(e -> new CoreSpaceExcelBo(e.getKey(), e.getValue()))
.collect(Collectors.toList())));
```
这段代码将原始的Map对象中的每个List对象进行处理,将其中的元素根据CartonCode字段进行分组,并且统计每个组中CoreSpaceExcelBo对象的num字段的总和。然后,将这些统计结果封装成新的CoreSpaceExcelBo对象,并存储在新的List中。最后,将这个新的List作为Map中每个键所对应的值。