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

Java Stream判断List<Integer>包含指定Integer时结果异常问题排查

问题原因与解决方法

你犯的核心错误是误用了Stream.of()方法:
当你传入List<Integer>给Stream.of()时,它不会将列表中的元素拆分成流的元素,而是把整个List对象作为流的唯一元素。这时候anyMatch判断的是「这个List对象是否等于目标Integer值」,显然永远返回false。

正确的两种写法:

  1. 用List自带的stream()方法创建元素流
Integer targetId = Integer.parseInt(documentId);
boolean exists = userObj.getUserDocIdsToView()
    .stream()
    .anyMatch(id -> id.equals(targetId));
  1. 直接用List的contains()方法(更简洁,无需Stream)
Integer targetId = Integer.parseInt(documentId);
boolean exists = userObj.getUserDocIdsToView().contains(targetId);

错误代码对比(方便你理解差异):

// 错误写法:Stream中仅包含一个List<Integer>对象,而非列表里的每个Integer
boolean exists = Stream.of(userObj.getUserDocIdsToView())
    .anyMatch(id -> id.equals(targetId)); // 此处id的类型是List<Integer>,和Integer不相等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 04:42:36