Java Stream判断List<Integer>包含指定Integer时结果异常问题排查
问题原因与解决方法
你犯的核心错误是误用了Stream.of()方法:
当你传入List<Integer>给Stream.of()时,它不会将列表中的元素拆分成流的元素,而是把整个List对象作为流的唯一元素。这时候anyMatch判断的是「这个List对象是否等于目标Integer值」,显然永远返回false。
正确的两种写法:
- 用List自带的
stream()方法创建元素流
Integer targetId = Integer.parseInt(documentId); boolean exists = userObj.getUserDocIdsToView() .stream() .anyMatch(id -> id.equals(targetId));
- 直接用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
相关产品推荐
相关产品推荐

