Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream filter null pointer issue

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?

like image 889
uksz Avatar asked Sep 23 '16 06:09

uksz


People also ask

How do I stop NullPointerException in streams?

In any of the cases your code is going to throw a NullPointerException. The exception can be avoided by adding Null checks.

How do I fix null pointer in Java?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

How do I filter null values in stream?

We can use lambda expression str -> str!= null inside stream filter() to filter out null values from a stream.


1 Answers

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());
like image 54
uksz Avatar answered Sep 20 '22 19:09

uksz