filter with null Safety
What you'll learn: How to prevent NullPointerException errors when filtering streams that might contain null elements.
The Problem with Nulls in Streams
When you use filter on a stream, you're calling methods or accessing properties on each element through your predicate. But what happens if the stream contains null values? You'll get a NullPointerException the moment your predicate tries to work with a null element.
Think of it like a quality control inspector: If you try to measure the weight of packages on a conveyor belt, but some "packages" are actually empty spaces (nulls), your scale will malfunction when it encounters them. You need to check "is there actually a package here?" before attempting to weigh it.
Handling Nulls Safely
The solution is to incorporate null checks directly into your filter predicate logic. You have two common patterns:
Pattern 1: Filter out nulls first
list.stream()
.filter(item -> item != null)
.filter(item -> item.getPrice() > 100)
Pattern 2: Null check within the predicate
list.stream()
.filter(item -> item != null && item.getPrice() > 100)
Both approaches work, but Pattern 2 is more concise when you have a single filtering condition. Pattern 1 is clearer when you have multiple filtering stages, as it explicitly removes nulls upfront.
Practical Example
List<String> names = Arrays.asList("Alice", null, "Bob", null, "Carol");
List<String> longNames = names.stream()
.filter(name -> name != null && name.length() > 3)
.collect(Collectors.toList());
// Result: ["Alice", "Carol"]
Without the name != null check, this code would crash when trying to call length() on a null value.
Key Takeaway: Always guard against null values in your filter predicates using explicit null checks (!= null) before accessing methods or properties, preventing NullPointerException errors in your stream pipelines.