Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: Getting a property from a List of a List

Tags:

I am new in Java 8, and I want to get the first Phone that is not null from a list of contacts form a list of persons, but I am getting a incompatible types error

return segadors
                .stream()
                .map(c -> c.getSegadorMedium().stream().map(cm -> Objects.nonNull(cm.getPhoneSegador())))
                .findFirst()
                .orElse(null);
like image 749
Sandro Rey Avatar asked Jul 08 '19 14:07

Sandro Rey


1 Answers

  return segadors
            .stream()
            .flatMap(c -> c.getSegadorMedium().stream().filter(cm -> Objects.nonNull(cm.getPhoneSegador())))
            .findFirst()
            .orElse(null);

You need a filter in that Objects.nonNull check; plus since you are returning a Stream, you need a flatMap just before that

like image 63
Eugene Avatar answered Nov 15 '22 04:11

Eugene