Sandro Rey
Sandro Rey

Reputation: 2989

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

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

Upvotes: 5

Views: 90

Answers (1)

Eugene
Eugene

Reputation: 120968

  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

Upvotes: 4

Related Questions