I have this piece of code
List<BookDto> deskOfficer =
delegationExtendedDto
.stream()
.filter(Objects::nonNull)
.filter(d -> d.getMembers() !=null && !d.getMembers().isEmpty())
.map(d -> d.getMembers()
.stream()
.filter(Objects::nonNull)
.filter(m -> RolesEnum.RESPONSIBLE_ADMIN.equals(m.getRole())))
.collect(Collectors.toList());
but I have a compilation error
Type mismatch: cannot convert from List<Stream<BookDto>> to List<BookDto>
Collectors is a final class that extends Object class. It provides reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc. Java Collectors class provides various methods to deal with elements. Methods.
collect() is one of the Java 8's Stream API's terminal methods. It allows us to perform mutable fold operations (repackaging elements to some data structures and applying some additional logic, concatenating them, etc.) on data elements held in a Stream instance.
You seem to be looking for flatmap
as :
List<BookDto> deskOfficer = delegationExtendedDto
.stream()
.filter(Objects::nonNull)
.filter(d -> d.getMembers() != null) // stream would handle the empty case
.flatmap(d -> d.getMembers().stream()) // <<< here -- the stream objects are different
.filter(Objects::nonNull)
.filter(m -> RolesEnum.RESPONSIBLE_ADMIN.equals(m.getRole())))
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With