In this specific example, I think @Tagir is 100% correct, put it in one filter and do two checks. I would not use Optional.ofNullable Optional - it really is that the return data types should not follow the logic ... but in fact, neither here nor there.
I would like to note that java.util.Objects has a good method for doing this in the broad case, so you can do this:
cars.stream() .filter(Objects::nonNull)
Which will clear your null objects. For those unfamiliar, this is a shorthand for the following:
cars.stream() .filter(car -> Objects.nonNull(car))
To partially answer the question, we will return the list of car names that starts with the letter "M" :
cars.stream() .filter(car -> Objects.nonNull(car)) .map(car -> car.getName()) .filter(carName -> Objects.nonNull(carName)) .filter(carName -> carName.startsWith("M")) .collect(Collectors.toList());
Once you get used to the shortened lambda, you can also do this:
cars.stream() .filter(Objects::nonNull) .map(Car::getName)
Unfortunately, as soon as you .map(Car::getName) you will only return a list of names, not cars. So less beautiful, but fully answers the question:
cars.stream() .filter(car -> Objects.nonNull(car)) .filter(car -> Objects.nonNull(car.getName())) .filter(car -> car.getName().startsWith("M")) .collect(Collectors.toList());
xbakesx May 23 '16 at 9:39 PM 2016-05-23 21:39
source share