Use lambda in Java8 to filter the value when it is not null

This list is filtered based on some parameters using Java 8. But if the parameter is null, a NullPointerException is thrown. How to filter out null values

List<String> carsFiltered = Optional.ofNullable(cars)
            .orElseGet(Collections::emptyList)
            .stream()
            .filter(Objects::nonNull) //filtering car object that are null
            .map(Car::getName) //now it's a stream of Strings
            .filter(Objects::nonNull) //filtering null in Strings
            .filter(name -> name.startsWith("M"))
            .collect(Collectors.toList()); //back to List of Strings

Guess you like

Origin blog.51cto.com/1929297/2603621