Filter values only if not null using lambda in Java8

I have a list of objects say car. I want to filter this list based on some parameter using Java 8. But if the parameter is null, it throws NullPointerException. How to filter out null values?

Current code is as follows

requiredCars = cars.stream().filter(c -> c.getName().startsWith("M"));

This throws NullPointerException if getName() returns null.

6 Answers
6

Leave a Comment