JB Nizet answer is okay, but it uses map only for its side effects and not for the mapping operation, which is kind of weird. There is a method which can be used when you are solely interested in the side effects of something, such as throwing an exception: peek.

List<Parent> filtered = list.stream()
    .peek(Objects::requireNonNull)
    .filter(predicate)
    .collect(Collectors.toList());

And if you want your own exception just put a lambda in there:

List<Parent> filtered = list.stream()
    .peek(p -> { if (p == null) throw new MyException(); })
    .filter(predicate)
    .collect(Collectors.toList());

Note about non exhausted streams

Note that, regardless of if you use map or peek, you have to make sure that the stream is consumed in its entirety for all the elements to be checked! Otherwise the exception might not be thrown even if there are null elements.

Examples where all elements might not be checked:

  • limit is used.
  • allMatch is used.
  • The stream is filtered BEFORE the null check pipeline stage.

Checked Exceptions

If your exception is checked you can either check for null beforehand, if you don't mind traversing the list twice. This is probably best in your case, but might not always be possible.

if (list.contains(null)) throw new MyCheckedException();

You could also throw an unchecked exception in your stream pipeline, catch it and then throw the checked one:

try {
    ...
        .peek(p -> { if (p == null) throw new MyException(); })
    ...
} catch (MyException exc) {
    throw new MyCheckedException();
}
Answer from Lii on Stack Overflow
Top answer
1 of 4
24

JB Nizet answer is okay, but it uses map only for its side effects and not for the mapping operation, which is kind of weird. There is a method which can be used when you are solely interested in the side effects of something, such as throwing an exception: peek.

List<Parent> filtered = list.stream()
    .peek(Objects::requireNonNull)
    .filter(predicate)
    .collect(Collectors.toList());

And if you want your own exception just put a lambda in there:

List<Parent> filtered = list.stream()
    .peek(p -> { if (p == null) throw new MyException(); })
    .filter(predicate)
    .collect(Collectors.toList());

Note about non exhausted streams

Note that, regardless of if you use map or peek, you have to make sure that the stream is consumed in its entirety for all the elements to be checked! Otherwise the exception might not be thrown even if there are null elements.

Examples where all elements might not be checked:

  • limit is used.
  • allMatch is used.
  • The stream is filtered BEFORE the null check pipeline stage.

Checked Exceptions

If your exception is checked you can either check for null beforehand, if you don't mind traversing the list twice. This is probably best in your case, but might not always be possible.

if (list.contains(null)) throw new MyCheckedException();

You could also throw an unchecked exception in your stream pipeline, catch it and then throw the checked one:

try {
    ...
        .peek(p -> { if (p == null) throw new MyException(); })
    ...
} catch (MyException exc) {
    throw new MyCheckedException();
}
2 of 4
4

Let’s start with the simplest solution:

if(list.contains(null)) throw new MyException();
result = list.stream().filter(predicate).collect(Collectors.toList());

If you suspect the list to contain nulls and even have a specialized exception type to flag this condition, a pre-check is the cleanest solution. This ensures that such condition doesn’t silently remain if the predicate changes to something that can handle nulls or when you use a short-circuiting stream operation that may end before encountering a subsequent null.

If the occurrence of null in the list still is considered a programming error that shouldn’t happen, but you just want to change the exception type (I can’t imagine a real reason for this), you may just catch and translate the exception:

try {
    result = list.stream().filter(predicate).collect(Collectors.toList());
}
catch(NullPointerException ex) {
    if(list.contains(null)) // ensure that we don’t hide another programming error
        throw new MyException();
    else throw ex;
}

This works efficient under the assumption that null references do not occur. As said, if you suspect the list to contain null you should prefer a pre-check.

🌐
Stack Overflow
stackoverflow.com › questions › 73201750 › null-pointer-exception-while-consuming-streams
java 8 - Null pointer exception while consuming streams - Stack Overflow
request.getRules().stream() .flatMap(ruleDTO -> ruleDTO.getGrades().stream()) .map(gradeDTO -> gradeDTO.getHierarchyCode()) .forEach(hierarchyCode -> { //I'm doing some business logic here Optional<SomePojo> dsf = someList.stream() .filter(pojo -> hierarchyCode.equals(pojo.getId())) // lets say pojo.getId() returns 200 .findFirst(); System.out.println(dsf.get().getCode()); }); So in the first iteration for the expected output it returns 33, but in the second iteration it is failing with Null pointer instead of just skipping the loop since "grades" array is empty this time. How do I handle the null pointer exception here? java-8 ·
🌐
DZone
dzone.com › coding › java › avoiding nullpointerexception in java 8
Avoiding NullPointerException in Java 8
August 26, 2019 - In this post, we explore some simple strategies to avoid the NullPointerException. Let's get started. Different languages provide different methods for checking. Unfortunately, Java is not among them. So, we have to check our variables and objects beforehand. Back in Java 7, there was a proposal to add a simplified method that checked for this exception.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-avoid-nullpointerexception-in-java-using-optional-class
How to avoid NullPointerException in Java using Optional class? - GeeksforGeeks
August 6, 2025 - // Java program to avoid NullPointerException // using Optional Class import java.util.Optional; public class Example { public static void main(String[] args) { // Create a String of size 10 String[] a = new String[10]; // Create an Optional Class instance // and get the state for a[1] element // for Null value Optional<String> check = Optional.ofNullable(a[1]); // If the value in the current instance is null, // it will return false, else true if (check.isPresent()) { // The String is empty // So a[1] will have null at present String upcase = a[1].toUpperCase(); System.out.print(upcase); } else // As the current value is null System.out.println("String value is not present"); } } ... String value is not present Note: Hence this can be understood as an exception handling method for NullPointerException NullPointerException Handling using Optional class:
🌐
Baeldung
baeldung.com › home › java › java streams › handling nullpointerexception in findfirst() when the first element is null
Handling NullPointerException in findFirst() When the First Element Is Null | Baeldung
January 10, 2024 - To avoid NullPointerException when using findFirst() in Java, filter the stream before calling findFirst() or use Optional#ofNullable() to wrap values in an Optional object.
🌐
amitph
amitph.com › home › java › avoid nullpointerexception using java optional
Avoid NullPointerException using Java 8 Optional | amitph
November 22, 2024 - On top of this, Java Optional provides convenient methods to access the object value, return defaults, throw exceptions, or perform null checks. A Java method or a POJO should use the Optional type for potentially null objects meant for external consumption. For example, a field in a POJO or return type of a method. Their consumers can use the Optional instance to safely access the object without dealing with the null values or checks. // Consumer needs to handle nulls proactively.
🌐
Techie Delight
techiedelight.com › home › java › filter null values from stream in java
Filter null values from Stream in Java | Techie Delight
July 7, 2026 - This post will discuss how we can filter null values from the stream in Java 8 and above. Many operations on streams will throw a `NullPointerException` if any null values are present in it.
Find elsewhere
🌐
How to do in Java
howtodoinjava.com › home › exception handling › java nullpointerexception
Handling Java NullPointerException and Best Practices
October 1, 2022 - Instead use String.valueOf(object). Even if the object is null in this case, it will not give an exception and will print ‘null‘ to the output stream. An awesome tip to avoid NPE is to return empty strings or empty collections rather than null. Java 8 Optionals are a great alternative here.
🌐
DEV Community
dev.to › arpitmandliya › java-8-optional-a-way-to-avoid-nullpointerexception-10g1
Java 8 Optional: A way to avoid NullPointerException - DEV Community
April 11, 2019 - What are the cases it’s good for. You might want to explore using it with map() it’s a powerful tool. ... Thanks for sharing! ... Yes, Optional.of will throw an Exception if you pass a null value.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › NullPointerException.html
NullPointerException (Java Platform SE 8 )
July 21, 2026 - Applications should throw instances of this class to indicate other illegal uses of the null object. NullPointerException objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable · Submit a bug or feature For further API reference ...
🌐
Medium
supakon-k.medium.com › 4-ways-to-handle-null-objects-in-java-7e2596c235d
4 ways to handle NullPointerException in Java | by Supakon_k | Medium
August 5, 2022 - When assigning value to the object and checking exceptions simultaneously, it is easy to use. ... String result = list.stream() .filter(value -> value.contains("A")) .findFirst() .orElseThrow(() -> new NullPointerException("data is null"));
🌐
CodingTechRoom
codingtechroom.com › question › -handle-null-values-java-8-streams
How to Handle Null Values in Java 8 Streams - CodingTechRoom
Solution: Always apply a `filter(Objects::nonNull)` before operations that could cause null pointer exceptions. Mistake: Using `collect(Collectors.toList())` without filtering, which can retain null values.
🌐
Medium
medium.com › codimis › strategies-to-avoid-nullpointerexceptions-for-null-safe-stream-operations-in-java-f1fe6f025476
Strategies to Avoid NullPointerExceptions for Null-Safe Stream Operations in Java | by Uğur Taş | Codimis
April 30, 2024 - Even though Java 14 introduced the NullPointerException.getMessage() method to provide more detailed information about the cause of the NPE, preventing these exceptions in the first place is always the best approach.
🌐
Stack Overflow
stackoverflow.com › questions › 54636929 › java-stream-with-null-pointer-exception
nullpointerexception - Java Stream With null pointer Exception - Stack Overflow
February 12, 2019 - import java.util.*; import java.util.stream.Collectors; public class Main { public static void main( String[] args ) { MemberList list = new MemberList( ); List< Member > memberList = new ArrayList<>( ); for ( int i = 0; i < 10; i++ ) { Member member = new Member( ); member.setAge( 10 + "" ); member.setName( null ); member.setGender( null ); memberList.add( member ); } Member member = null; memberList.add( member ); Member m = new Member( ); m.setGender( "MALE" ); list.setMember( memberList ); list.setCount( 10 ); list.getMember( ) .stream( ) .filter( obj -> Objects.nonNull( obj ) ) .filter( obj -> Objects.nonNull( obj.getGender( ) ) ) .filter( obj -> obj.getGender( ) .equals( "MALE" ) ) .collect( Collectors.toList( ) ); } }
🌐
Questionsforinterview
questionsforinterview.in › handling-nullpointerexception-in-java-8-streams
Questionsforinterview
September 13, 2019 - Enums allow angular developers to write more maintainable code, Here is a case where we can reuse a enum across the application which brings more maintainability and less bugs into our code.
🌐
Baeldung
baeldung.com › home › java › java streams › java null-safe streams from collections
Java Null-Safe Streams from Collections | Baeldung
May 11, 2024 - Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use. But these can also be overused and fall into some common pitfalls. To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams: ... In this tutorial, we’ll learn how to create null-safe streams from Java collections.