Java Stream How to - Filter non null value








Question

We would like to know how to filter non null value.

Answer

/*from w  w  w. ja va 2  s. com*/
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Chris", "HTML", "XML", "CSS","");

        Stream<String> s = names.stream().filter(name -> name.startsWith("C"));

        List<String> collect = s.filter(Objects::nonNull).collect(Collectors.toList());
        System.out.println(collect);
    }
}

The code above generates the following result.