遍历List<Object>流时出现NoSuchElementException问题求助
解决Java Stream中NoSuchElementException问题
你遇到的NoSuchElementException是因为filter后的流没有匹配到任何元素,直接调用iterator().next()会强制获取元素,自然抛出异常。这和你用==比较long类型无关:
- 如果
getId()返回的是基本类型long,用==完全合法; - 如果是包装类
Long,建议用equals()或者拆箱后用==(比如mpProductFeedback.getId().longValue() == mpProductFeedbackId),避免对象引用不同导致的判断错误,但这不是当前异常的诱因。
修复方案
不要直接使用iterator().next(),改用Stream的findFirst()方法,它返回Optional对象,能安全处理空结果:
替换这段风险代码:
.filter(mpProductFeedback -> mpProductFeedback.getId()==mpProductFeedbackId) .iterator() .next()
为以下两种方式之一:
方式1:返回默认值(无匹配时用预设对象兜底)
.filter(mpProductFeedback -> mpProductFeedback.getId() == mpProductFeedbackId) .findFirst() .orElse(new MpProductFeedback()) // 替换为你的默认空对象
方式2:抛出自定义异常(无匹配时触发业务错误)
.filter(mpProductFeedback -> mpProductFeedback.getId() == mpProductFeedbackId) .findFirst() .orElseThrow(() -> new RuntimeException("未找到ID为" + mpProductFeedbackId + "的反馈记录"))
额外优化
开头的.stream().iterator().next()同样存在空集合风险,建议同步优化:
findAllByBarcode.stream() .findFirst() .orElseThrow(() -> new RuntimeException("未找到对应条码的记录")) .getMpProductFeedbacks() ...
内容的提问来源于stack exchange,提问作者Alex Kas
相关产品推荐
相关产品推荐

