Java stream filter null pointer issue


March 2019


3.2k time


I have the following stream:

services =
        .filter(service -> (service.getType().isEmpty() || service.getType().equals(type)))

where service.type is string, and type is also a string. My filter should return all services with its type equal to null (or simply blank), or the given type.

This throws me an error of:

java.lang.NullPointerException: null at com.eternity.service.OrderService.lambda$getServicesForOrder$0( ~[classes/:na] at$2$1.accept( ~[na:1.8.0_77] at java.util.ArrayList$ArrayListSpliterator.forEachRemaining( ~[na:1.8.0_77] at ~[na:1.8.0_77] at ~[na:1.8.0_77] at$ReduceOp.evaluateSequential( ~[na:1.8.0_77] at ~[na:1.8.0_77] at ~[na:1.8.0_77] at com.eternity.service.OrderService.getServicesForOrder( ~[classes/:na]

What am I missing?

1 answers


The issue was: I was using .isEmpty() on a null object. I had to use StringUtils.isEmpty() method:

services =
        .filter(service -> (StringUtils.isEmpty(service.getType()) || service.getType().equals(type)))