流内不同数字类型的转换/比较

can*_*ble 4 java collections java-stream

我再次遇到Stream API的问题.我试图实现的功能并不是最困难的事情,但由于存在不兼容的类型而我无法过滤,因此我不知道如何使比较正确.这个想法是获取有关给定部分链接到的部门的信息.

department.getSectionId()返回Longwhile Section::getIdInteger(我无法更改)

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());
}
Run Code Online (Sandbox Code Playgroud)

当然,主谓词的结果总是错误的.我知道代码很糟糕,而且我没有正确定义条件,但我希望你能得到这个想法.也许有可能以某种方式合并这些集合或以聪明的方式进行比较.

先感谢您!

GBl*_*ett 6

截至目前,您正在比较a Long和a Steam<Integer>将始终返回false.

您可以稍微翻转逻辑并使用a 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());
}
Run Code Online (Sandbox Code Playgroud)

这将转换Section::getId为a Stream<Long>,然后通过过滤Stream来查看是否有任何department.getSectionId等于Id.