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

Sandro Rey :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=121261&siteId=1