Conversion/comparison of different numeric types inside streams

  • A+
Category:Languages

I'm having a problem with Stream API... again. The functionality I'm trying to implement isn't the hardest thing, but I'm having difficulties filtering since there are incompatible types and I don't how to make the comparison right. The idea is to get information about departments which the given sections are linked to.

department.getSectionId() returns Long while Section::getId is an Integer (which I can't change)

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()); } 

Of course the result of the main predicate is always false. I know the code is awful and I'm not defining conditions right, but I hope you get the idea. Maybe there's a possibility to somehow merge these collections or compare in a smart way.

Thank you in advance!

 


As of now you are comparing a Long and a Steam<Integer> which will always return false.

You can flip around your logic a little and use a mapToLong to convert the int's to Long's:

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()); } 

This will convert Section::getId to a Stream<Long>, and then filter through the Stream to see if any of the department.getSectionId equals the Id.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: