我再次遇到Stream API问题。我尝试实现的功能并不是最困难的事情,但是由于类型不兼容,并且在进行正确比较时,我在过滤方面遇到了困难。这个想法是获得有关给定部分链接到的部门的信息。department.getSectionId()
返回Long
,而Section::getId
是Integer
(我无法更改)
private List<DepartmentInfo> retrieveLinkedDepartments(final Collection<Section> sections) {
return this.departmentDao
.findAll()
.stream()
.filter(department -> department.getSectionId() != null)
.filter(department -> department.getSectionId().equals(sections.stream().map(Section::getId)))
.map(this.departmentInfoMapper::map)
.collect(Collectors.toList());
}
当然,主谓词的结果始终为假。我知道代码很糟糕,而且我没有正确定义条件,但希望您能理解。也许有可能以某种方式合并这些集合或以明智的方式进行比较。
先感谢您!
最佳答案
到目前为止,您正在比较Long
和Steam<Integer>
,它们将始终返回false。
您可以稍微翻转一下逻辑,然后使用mapToLong
将int转换为Long
:
private List<DepartmentInfo> retrieveLinkedDepartments(final Collection<Section> sections) {
return this.departmentDao
.findAll()
.stream()
.filter(department -> department.getSectionId() != null)
.filter(department -> sections.stream()
.mapToLong(Section::getId)
.anyMatch(department.getSectionId()::equals))
.map(this.departmentInfoMapper::map)
.collect(Collectors.toList());
}
这会将
Section::getId
转换为Stream<Long>
,然后对Stream
进行过滤以查看department.getSectionId
是否等于ID。