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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | /** * 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:
1 2 3 4 5 6 7 8 9 | 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)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | /** * 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:
1 2 3 4 5 6 | 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:
- Double the even / odd numbers of a specified ArrayList using Streams
- Double the numbers of specified ArrayList using Streams
filter null values from stream
Useful References: