Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collecting Lists in Java 8

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>
like image 916
carles xuriguera Avatar asked Mar 13 '19 11:03

carles xuriguera


People also ask

What is a collector in Java 8?

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.

What is the use of collect in Java 8?

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.


1 Answers

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());
like image 178
Naman Avatar answered Sep 18 '22 02:09

Naman