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
相关产品推荐
相关产品推荐

