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?
In any of the cases your code is going to throw a NullPointerException. The exception can be avoided by adding Null checks.
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.
We can use lambda expression str -> str!= null inside stream filter() to filter out null values from a stream.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With