简体   繁体   中英

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. I already tried to check the stream entity for null, though it didn't work.

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. Splitting single huge .filter() operation to a few smaller ones makes your code much more readable and easier to maintain.

In this case we also make sure that every .getX() , .getY() and .getZ() does not return any null to avoid NullPointerException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM