You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java遍历对象数组提取指定double字段并适配方法参数的方案

解决方案

1. 解决类型不匹配问题

你需要调用AtomicReference<Double>的get()方法获取内部包装的Double对象,再利用Java自动拆箱特性转为double类型传入方法。同时要处理discountPrice为空的情况,避免空指针异常:

修改后的传参代码:

cart.getItems().forEach(cartItem -> {
    CreateOrderDto.ItemDto item = new CreateOrderDto.ItemDto();
    // 获取AtomicReference中的值,为空则设默认值(比如0.0)
    Double price = discountPrice.get();
    item.setDiscountPrice(price != null ? price : 0.0);
});

或者简化为一行:

item.setDiscountPrice(discountPrice.get() != null ? discountPrice.get() : 0.0);

2. 优化取值逻辑(可选)

你当前的遍历代码会将discountPrice覆盖为最后一个元素的值,如果需求是处理每个元素的discountPrice而非仅保留最后一个,可调整遍历逻辑:

直接遍历listItems处理每个元素的折扣价:

listItems.forEach(dc -> {
    CreateOrderDto.ItemDto item = new CreateOrderDto.ItemDto();
    Double price = dc.getDiscountPrice();
    item.setDiscountPrice(price != null ? price : 0.0);
    // 后续处理item逻辑...
});

单线程环境下,也可以用数组替代AtomicReference存储值(同样满足lambda对有效final变量的要求):

Double[] discountPrice = {0.0};
listItems.forEach(dc -> {
    discountPrice[0] = dc.getDiscountPrice();
});
// 传参时同样对discountPrice[0]做空值判断后传入

内容的提问来源于stack exchange,提问作者justrying

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 07:48:45