Java流过滤器空指针问题

时间:2016-09-23 06:49:23

标签: java java-stream

我有以下信息流:

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

其中service.type是字符串,type也是字符串。我的过滤器应该返回所有服务,其type等于null(或者只是空白)或给定类型。

这引发了我的错误:

  

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)   〜[类/:NA]

我错过了什么?

1 个答案:

答案 0 :(得分:4)

问题是:我在空对象上使用.isEmpty()。我不得不使用StringUtils.isEmpty()方法:

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