In this tutorial, we will see how to filter the null values from a Stream in Java.
Example: A stream with null values
In this example, we have a stream with null values. Lets see what happens when we do not filter the null values.
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<String> list = Arrays.asList("Java", "Stream", null, "Filter", null); List<String> result = list.stream().collect(Collectors.toList()); result.forEach(System.out::println); } }
Output:
Java Stream null Filter null
As you can see that the null values are present in the output.
Java 8 Example: Filter null values from a stream
We can use lambda expression str -> str!=null inside stream filter() to filter out null values from a stream.
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<String> list = Arrays.asList("Java", "Stream", null, "Filter", null); List<String> result = list.stream() .filter(str -> str!=null) .collect(Collectors.toList()); result.forEach(System.out::println); } }
Output:
Java Stream Filter
Alternatively you can use method reference Objects::nonNull in the filter() method to filter out the null values like this:
List<String> result = list.stream() .filter(Objects::nonNull) .collect(Collectors.toList());
Java 8 Example 2: Filter null values after map intermediate operation
Similarly we can filter the null values after map operation on a stream.
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Example { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, null, 4, null, 5); List<Integer> result = list.stream() .map(num -> num) //here you will be having a different logic .filter(n -> n!=null) .collect(Collectors.toList()); result.forEach(System.out::println); } }
Output:
1 2 3 4 5
Leave a Reply