Java stream filter null pointer issue

Refresh

March 2019

Views

3.2k time

1

I have the following stream:

services = services.stream()
        .filter(service -> (service.getType().isEmpty() || service.getType().equals(type)))
        .collect(Collectors.toList());

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(OrderService.java:140) ~[classes/:na] at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:174) ~[na:1.8.0_77] at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374) ~[na:1.8.0_77] at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481) ~[na:1.8.0_77] at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471) ~[na:1.8.0_77] at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708) ~[na:1.8.0_77] at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:1.8.0_77] at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499) ~[na:1.8.0_77] at com.eternity.service.OrderService.getServicesForOrder(OrderService.java:141) ~[classes/:na]

What am I missing?

1 answers

4

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

services = services.stream()
        .filter(service -> (StringUtils.isEmpty(service.getType()) || service.getType().equals(type)))
        .collect(Collectors.toList());