用Java 8收集列表

时间:2019-03-13 11:00:40

标签: java java-8 functional-programming java-stream

我有这段代码

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

但是我有一个编译错误

Type mismatch: cannot convert from List<Stream<BookDto>> to List<BookDto>

1 个答案:

答案 0 :(得分:8)

您似乎在寻找flatmap为:

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