[英]JAVA Querying the list of data using Stream filter,null pointer exception
List<Data>data = Datalist.stream()
.filter(o -> o.getX().equals(data.getX()) &&
o.getY().equals(data.getMwSchemeCode().getY()) &&
o.getZ().equals(o.getZ()))
.collect(Collectors.toList);
When I run this code a Null pointer exception occurs. 当我运行此代码时,将发生Null指针异常。 I already tried to check the stream entity for null, though it didn't work.
我已经尝试检查流实体是否为null,尽管它不起作用。
Try simplifying your stream calls to something like this: 尝试简化对以下内容的流调用:
List<Data> data = datalist.stream()
.filter(Objects::nonNull)
.filter(o -> Objects.nonNull(o.getX()) && o.getX().equals(data.getX()))
.filter(o -> Objects.nonNull(o.getY()) && Objects.nonNull(data.getMwSchemeCode()) && o.getY().equals(data.getMwSchemeCode().getY()))
.filter(o -> Objects.nonNull(o.getZ()) && o.getZ().eqauls(data.getZ()))
.collect(Collectors.toList());
The good thing about streams is that every stream operation is lazy-evaluated, which means that all operations will be triggered in terminating .collect(Collectors.toList())
call. 关于流的好处是,每个流操作都是惰性求值的,这意味着所有操作都将在终止
.collect(Collectors.toList())
调用时触发。 Splitting single huge .filter()
operation to a few smaller ones makes your code much more readable and easier to maintain. 将单个巨大的
.filter()
操作拆分为几个较小的操作,可使您的代码更具可读性且更易于维护。
In this case we also make sure that every .getX()
, .getY()
and .getZ()
does not return any null
to avoid NullPointerException
. 在这种情况下,我们还要确保每个
.getX()
.getY()
和.getZ()
都不会返回任何null
以避免NullPointerException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.