In this tutorial, we will see “How to filter Null values from a Stream in Java 8”. stream filter not null stream filter not null stream filter not null stream filter not null stream filter not null stream filter not null 

But, before jumping onto the solution directly, let’s see how a stream looks when it has the null values in it.

Filter/Remove null values from a List using Stream in Java 8...!!! Share on X

Stream with Null Values

/**
 * Stream with Null values
 * @author Deepak Verma
 */
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamOfNullValues {

    public static void main(String[] args) {

        Stream<String> sports = Stream.of("soccer", "basketball", null, "cricket", "badminton", null, "volleyball", null, "Swimming");

        List<String> result = sports.collect(Collectors.toList());

        result.forEach(System.out::println);

    }
}

 

Output:

soccer
basketball
null
cricket
badminton
null
volleyball
null
Swimming

If you see above, there are NULL values in the output but now in the solution  below, we are going to get rid of them. So, let’s do it. 

 

Solution: Filter the NULL values from Stream (example)

/**
 * Filter Null values from the Stream
 * @author Deepak Verma
 */
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Filter_Null_Values_From_Stream_Example {

    public static void main(String[] args) {

        Stream<String> sports = Stream.of("soccer", "basketball", null, "cricket", "badminton", null, "volleyball", null, "Swimming");

        //use filter (str -> str!=null) to remove the nulls
        List<String> result = sports.filter(str -> str!=null).collect(Collectors.toList());

        result.forEach(System.out::println);

    }
}

 

Output:

soccer
basketball
cricket
badminton
volleyball
Swimming

Now, If you see above, NULL values are no longer present in the output. 

stream filter not null

Filter/Remove null values from a List using Stream in Java 8...!!! Share on X

Do you like this Post? – then check my other helpful posts:

 filter null values from stream

Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts