8

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
  • Did you try to debug ? Never tried on a lambda expression to be fair. Commented Sep 23, 2016 at 6:56

2 Answers 2

8

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());
Sign up to request clarification or add additional context in comments.

2 Comments

You could have also pre-filtered out the null objects with .filter(Objects::nonNull)
In case the whole object is not null, the attribute you are trying to access might be null. As here service.getType could give a null value. Can be filtered with .filter(service -> service.getType() != null)
0

Too late for an answer but still posting this here if anyone comes across this post. Try to use filter out all the objects which are null or have some property that can be null, before performing any operations on the same.
In this case

list.stream()
    //.filter(Objects::nonNull) // use when the whole object can be null    
    .filter(service->Objects.nonNull(service.getType()))
    .filter(service -> (service.getType().isEmpty() || service.getType().equals("Type1")))
    .collect(Collectors.toList());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.